接口方法会自动触发结构体的调用
时间:2024-02-28
浏览:261
作者:佚名
目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《接口方法会自动触发结构体的调用》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~
问题内容
我通过 go 编程语言学习了 golang。
package io
// writer is the interface that wraps the basic write method.
type writer interface {
// write writes len(p) bytes from p to the underlying data stream.
// it returns the number of bytes written from p (0 <= n <= len(p))
// and any error encountered that caused the write to stop early.
// write must return a non-nil error if it returns n < len(p).
// write must not modify the slice data, even temporarily.
//
// implementations must not retain p.
write(p []byte) (n int, err error)
}
第七章有一个例子,定义了一个bytecounter类型,并实现了io.writer接口的write方法。
type bytecounter int
func (c *bytecounter) write(p []byte) (int, error) {
*c += bytecounter(len(p)) // convert int to bytecounter
return len(p), nil
}
接下来实例化bytecounter,执行write方法,于是write方法计算出'hello'的长度,并赋值给c的指针,这样c的值就变成了5。这里我明白了
var c bytecounter
c.write([]byte("hello"))
fmt.println(c) // "5", = len("hello")
我一下子就听不懂了
func fprintf(w io.writer, format string, args ...interface{}) (int, error)
上面的fprintf源码,下面的例子中,因为&bytecounter实现了write方法,所以可以像io.write接口一样作为fprintf的第一个参数。然后执行fprintf,c的值变成12,也就是'hello, dolly'的长度。这个变化是因为执行了bytecounter的write方法。为什么这里没有调用就自动执行了呢?流程是怎样的?
c = 0 // reset the counter
var name = "Dolly"
fmt.Fprintf(&c, "hello, %s", name)
fmt.Println(c) // "12", = len("hello, Dolly")
非常感谢
解决方案
如果你查看源代码,你会看到:
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrintf(format, a)
n, err = w.Write(p.buf)
p.free()
return
}
因此,当您调用 fprintf 时,内部会调用 write。
https://github.com/golang/go/blob/go1.16.2/src/fmt/print.go#L202-L208
终于介绍完啦!小伙伴们,这篇关于《接口方法会自动触发结构体的调用》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
