為了實(shí)際更改struct方法中的字段,您需要一個(gè)指針類型的接收器。我明白那個(gè)。為什么我不能滿足io.Writer具有指針接收器的接口,以便我可以更改結(jié)構(gòu)字段?有沒有慣用的方法來做到這一點(diǎn)?// 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)}該代碼產(chǎn)生此錯(cuò)誤: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界面要求,也可以對(duì)實(shí)際的struct. 如果我將 Write 方法更改為值接收器 ( func (cw CountWriter) Write...),我可以避免錯(cuò)誤,但值不會(huì)增加。:(https://play.golang.org/p/pEUwwTj0zrb
1 回答

qq_花開花謝_0
TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
boo
不實(shí)現(xiàn)接口,因?yàn)?Write takes*CountWriter
而不是 aCountWriter
但是,&boo
Write 會(huì)接受,所以你必須傳遞它。
- 1 回答
- 0 關(guān)注
- 123 瀏覽
添加回答
舉報(bào)
0/150
提交
取消