我试图让一些Go对象实现io.Writer,但写入一个字符串而不是一个文件或类文件对象.我认为bytes.Buffer它会有效,因为它实现了Write(p []byte).但是,当我尝试这个:
import "bufio"
import "bytes"
func main() {
var b bytes.Buffer
foo := bufio.NewWriter(b)
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
cannot use b (type bytes.Buffer) as type io.Writer in function argument:
bytes.Buffer does not implement io.Writer (Write method has pointer receiver)
Run Code Online (Sandbox Code Playgroud)
我很困惑,因为它清楚地实现了界面.我该如何解决这个错误?
Kev*_*rke 133
将指针传递给缓冲区,而不是缓冲区本身:
import "bufio"
import "bytes"
func main() {
var b bytes.Buffer
foo := bufio.NewWriter(&b)
}
Run Code Online (Sandbox Code Playgroud)
aQu*_*Qua 17
package main
import "bytes"
import "io"
func main() {
var b bytes.Buffer
_ = io.Writer(&b)
}
Run Code Online (Sandbox Code Playgroud)
您不需要使用"bufio.NewWriter(&b)"来创建io.Writer.&b是io.Writer本身.
小智 9
只需使用
foo := bufio.NewWriter(&b)
因为 bytes.Buffer 实现 io.Writer 的方式是
func (b *Buffer) Write(p []byte) (n int, err error) {
...
}
// io.Writer definition
type Writer interface {
Write(p []byte) (n int, err error)
}
Run Code Online (Sandbox Code Playgroud)
是b *Buffer,不是b Buffer。(我也认为这很奇怪,因为我们可以通过变量或其指针调用方法,但我们不能将指针分配给非指针类型变量。)
此外,编译器提示不够清楚:
bytes.Buffer does not implement io.Writer (Write method has pointer receiver)
一些想法,去使用Passed by value,如果我们通过b到buffio.NewWriter(),在NewWriter(),它是一种新的b(一个新的缓冲区),而不是我们定义的原始缓冲区,因此,我们需要通过地址&b。
bytes.Buffer 定义为:
type Buffer struct {
buf []byte // contents are the bytes buf[off : len(buf)]
off int // read at &buf[off], write at &buf[len(buf)]
bootstrap [64]byte // memory to hold first slice; helps small buffers avoid allocation.
lastRead readOp // last read operation, so that Unread* can work correctly.
}
Run Code Online (Sandbox Code Playgroud)
using passed by value,传递的新缓冲区结构与原始缓冲区变量不同。
| 归档时间: |
|
| 查看次数: |
42653 次 |
| 最近记录: |