为了实际更改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 关注
- 76 浏览
添加回答
举报
0/150
提交
取消