对结构字段进行永久更改,并且*是否满足Writer接口?

时间:2018-09-10 15:22:52

标签: go interface

要在方法中实际更改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...),则可以避免该错误,但该值不会增加。 :(

https://play.golang.org/p/pEUwwTj0zrb

1 个答案:

答案 0 :(得分:0)

render('sender_info') if Rails.env.staging? 未实现该接口,因为Write使用boo而不是*CountWriter
但是,CountWriter将被Write接受,因此您必须通过它。