要在方法中实际更改struct
字段,您需要一个指针类型的接收器。 I understand that.
为什么我不能用指针接收器来满足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...
),则可以避免该错误,但该值不会增加。 :(
答案 0 :(得分:0)
render('sender_info') if Rails.env.staging?
未实现该接口,因为Write使用boo
而不是*CountWriter
但是,CountWriter
将被Write接受,因此您必须通过它。