英文:
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
implementsfunc (b *Buffer) Write(p []byte) (n int, err error)
, so it is of typeio.Writer
and can serve as parameter tofunc NewWriter(w io.Writer) *Writer
-
bytes.Buffer
also implementsfunc (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
, so it is of typeio.ReadFrom
, which enables the call forfmt.Println(w.ReadFrom(s))
-
as @akond mentioned
.(io.ReaderFrom)
is type assertion, and the expressionw, ok := bw.wr.(io.ReaderFrom)
asserts that thewr
field of theWriter
struct is also of typeio.ReaderFrom
For further reading check laws-of-reflection, it refers to similar code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论