为了实际更改struct
方法中的字段,您需要一个指针类型的接收器。我明白那个。
为什么我不能满足io.Writer具有指针接收器的接口,以便我可以更改结构字段?有没有惯用的方法来做到这一点?
// CountWriter is a type representing a writer that also counts
type 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
qq_花开花谢_0
相关分类