為了實際更改struct方法中的字段,您需要一個指針類型的接收器。我明白那個。為什么我不能滿足io.Writer具有指針接收器的接口,以便我可以更改結構字段?有沒有慣用的方法來做到這一點?// CountWriter is a type representing a writer that also countstype CountWriter struct { Count int Output io.Writer}func (cw *CountWriter) Write(p []byte) (int, error) { cw.Count++ return cw.Output.Write(p)}func takeAWriter(w io.Writer) { w.Write([]byte("Testing"))}func main() { boo := CountWriter{0, os.Stdout} boo.Write([]byte("Hello\n")) fmt.Printf("Count is incremented: %d", boo.Count) takeAWriter(boo)}該代碼產生此錯誤:prog.go:27:13: cannot use boo (type CountWriter) as type io.Writer in argument to takeAWriter: CountWriter does not implement io.Writer (Write method has pointer receiver)看來您既可以滿足Writer界面要求,也可以對實際的struct. 如果我將 Write 方法更改為值接收器 ( func (cw CountWriter) Write...),我可以避免錯誤,但值不會增加。:(https://play.golang.org/p/pEUwwTj0zrb
1 回答

qq_花開花謝_0
TA貢獻1835條經驗 獲得超7個贊
boo
不實現接口,因為 Write takes*CountWriter
而不是 aCountWriter
但是,&boo
Write 會接受,所以你必須傳遞它。
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消