【发布时间】:2021-03-27 03:39:33
【问题描述】:
我通过 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)
}
第7章有一个例子,定义了一个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")
非常感谢
【问题讨论】:
标签: go