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.
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.
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.