对结构字段进行持续更改*并*满足 Writer 接口?

为了实际更改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


慕神8447489
浏览 77回答 1
1回答

qq_花开花谢_0

boo不实现接口,因为 Write takes*CountWriter而不是 aCountWriter但是,&booWrite 会接受,所以你必须传递它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go