登录
首页 >  Golang >  Go问答

如何在实现 Writer 接口的同时对结构体字段进行持久更改?

来源:stackoverflow

时间:2024-03-04 20:15:27 288浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《如何在实现 Writer 接口的同时对结构体字段进行持久更改?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

为了实际更改方法中的 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


解决方案


boo 未实现该接口,因为 Write 采用 *CountWriter 而不是 CountWriter
但是,&boo 将被 Write 接受,因此您必须传递它。

今天关于《如何在实现 Writer 接口的同时对结构体字段进行持久更改?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>