亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對結構字段進行持續更改*并*滿足 Writer 接口?

對結構字段進行持續更改*并*滿足 Writer 接口?

Go
慕神8447489 2023-04-04 14:12:58
為了實際更改struct方法中的字段,您需要一個指針類型的接收器。我明白那個。為什么我不能滿足io.Writer具有指針接收器的接口,以便我可以更改結構字段?有沒有慣用的方法來做到這一點?// CountWriter is a type representing a writer that also countstype 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 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

boo不實現接口,因為 Write takes*CountWriter而不是 aCountWriter
但是,&booWrite 會接受,所以你必須傳遞它。



查看完整回答
反對 回復 2023-04-04
  • 1 回答
  • 0 關注
  • 110 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號