获取“bytes.Buffer不会实现io.Writer”错误信息 [英] Getting "bytes.Buffer does not implement io.Writer" error message
本文介绍了获取“bytes.Buffer不会实现io.Writer”错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让一些Go对象实现io.Writer,但是写入字符串而不是文件或文件类对象。我认为 bytes.Buffer
可以工作,因为它实现了 Write(p [] byte)
。然而,当我尝试这样做:
导入bufio
导入字节
()
var b bytes.Buffer
foo:
我得到以下错误:
不能使用b(类型bytes.Buffer)作为函数参数中的类型io.Writer:
bytes.Buffer没有实现io.Writer(Write方法有指针接收器)
我很困惑,因为它清楚地实现了界面。如何解决此错误?
解决方案传递指向缓冲区的指针,而不是缓冲区本身:
导入bufio
导入字节
func main(){
var b bytes.Buffer
writer:= bufio.NewWriter(&b)
}
I'm trying to have some Go object implement io.Writer, but writes to a string instead of a file or file-like object. I thought bytes.Buffer
would work since it implements Write(p []byte)
. However when I try this:
import "bufio"
import "bytes"
func main() {
var b bytes.Buffer
foo := bufio.NewWriter(b)
}
I get the following error:
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)
I am confused, since it clearly implements the interface. How do I resolve this error?
解决方案 Pass a pointer to the buffer, instead of the buffer itself:
import "bufio"
import "bytes"
func main() {
var b bytes.Buffer
writer := bufio.NewWriter(&b)
}
这篇关于获取“bytes.Buffer不会实现io.Writer”错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文