bufio.ReadWriter是具体类型,而不是接口。但是,它确实满足接口 (io.ReadWriter),因此可以将其分配给适当接口类型的变量/函数参数。然后它会按照您预期的方式工作(您的代码实际上不使用任何接口):
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
)
func readStuff(r io.Reader) {
b := make([]byte, 10)
n, err := r.Read(b)
if err != nil && err != io.EOF {
log.Fatal(err)
}
fmt.Printf("readStuff: %q\n", b[:n])
}
func writeStuff(w io.Writer) {
b := []byte("written")
n, err := w.Write(b)
if n != len(b) {
log.Fatal("Short write")
}
if err != nil {
log.Fatal(err)
}
}
func test(rw io.ReadWriter) {
readStuff(rw)
writeStuff(rw)
}
func main() {
r := io.Reader(bytes.NewBufferString("source"))
var uw bytes.Buffer
w := io.Writer(&uw)
rw := bufio.NewReadWriter(bufio.NewReader(r), bufio.NewWriter(w))
test(rw)
rw.Flush()
fmt.Printf("The underlying bytes.Buffer writer contains %q\n", uw.Bytes())
}
(也在这里)
输出:
readStuff: "source"
The underlying bytes.Buffer writer contains "written"
这种方式test
可以消耗任何io.ReadWriter
,而不仅仅是一个特定的。这暗示了您关于“哲学”的问题。