如何解释这个程序来实现接口。

huangapple go评论84阅读模式
英文:

how to explain this program to implement interface

问题

以下是翻译的内容:

请看这个源代码。

特别是这一段:

bw := NewWriter(b)
w, ok := bw.wr.(io.ReaderFrom)

我不明白b是字节元素,NewWriter()接受一个io.Writer。而bw.wr.(io.ReaderFrom)是什么意思?

".(io.ReaderFrom)"的函数是什么意思?

还有

fmt.Println(w.ReadFrom(s))

w是io.Writer,在io/io.go中,ReadFrom(s)是一个接口。

type ReaderFrom interface {
    ReadFrom(r Reader) (n int64, err error)
}

在这个源代码中,如何实现这个接口?

在这个源代码中,我找不到任何地方实现它。

英文:

https://play.golang.org/p/LHkVGzmC7N

look this source.

specilly this scrap:

bw := NewWriter(b)
w, ok := bw.wr.(io.ReaderFrom)

i dont understand b is bytes element,NewWrite() take a io.Writer。
and bw.wr.(io.ReaderFrom),how use is?

what's mean the ".(io.ReaderFrom)" 's function?

and

   fmt.Println(w.ReadFrom(s))

w is io.write,in io/io.go the ReadFrom(s) is interface.

type ReaderFrom interface {
    ReadFrom(r Reader) (n int64, err error)
}

how in this source can implement this interface?

in this source ,i cant find anywhere to implement.

答案1

得分: 2

这是一个类型断言

在你的情况下,它断言w不是nil,并且存储在w中的值是io.ReaderFrom接口类型。如果是这样,ok将为true,否则为false。这段代码没有检查ok变量,因为作者相信它将实现io.ReaderFrom接口。

英文:

It is a type assertion.

In your case it asserts that w is not nil and that the value stored in w is of interface io.ReaderFrom. ok is going to be true if it is, and false otherwise. This code doest not check ok variable because of the author's confidence it will be implementing io.ReaderFrom interface.

答案2

得分: 0

  • bytes.Buffer 实现了 func (b *Buffer) Write(p []byte) (n int, err error),因此它是 io.Writer 类型,并且可以作为参数传递给 func NewWriter(w io.Writer) *Writer

  • bytes.Buffer 还实现了 func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error),因此它是 io.ReadFrom 类型,这使得可以调用 fmt.Println(w.ReadFrom(s))

  • 正如 @akond 提到的,.(io.ReaderFrom) 是类型断言,表达式 w, ok := bw.wr.(io.ReaderFrom) 断言 Writer 结构体的 wr 字段也是 io.ReaderFrom 类型

要进一步了解,请查看 laws-of-reflection,它引用了类似的代码。

英文:
  • bytes.Buffer implements func (b *Buffer) Write(p []byte) (n int, err error), so it is of type io.Writer and can serve as parameter to func NewWriter(w io.Writer) *Writer

  • bytes.Buffer also implements func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error), so it is of type io.ReadFrom, which enables the call for fmt.Println(w.ReadFrom(s))

  • as @akond mentioned .(io.ReaderFrom) is type assertion, and the expression w, ok := bw.wr.(io.ReaderFrom) asserts that the wr field of the Writer struct is also of type io.ReaderFrom

For further reading check laws-of-reflection, it refers to similar code.

huangapple
  • 本文由 发表于 2017年7月25日 13:52:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/45294899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定