【问题标题】:The method that the structure implements the interface will be called automatically结构体实现接口的方法会被自动调用
【发布时间】: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


    【解决方案1】:

    如果你查看源代码,你会看到:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-21
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 2017-07-27
      相关资源
      最近更新 更多