go - 收到 "bytes.Buffer does not implement io.Writer"错误消息

标签 go

我正在尝试让一些 Go 对象实现 io.Writer,但写入的是字符串而不是文件或类似文件的对象。我认为 bytes.Buffer 会起作用,因为它实现了 Write(p []byte)。但是,当我尝试这样做时:

import "bufio"
import "bytes"

func main() {
    var b bytes.Buffer
    foo := bufio.NewWriter(b)
}

我收到以下错误:

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)

我很困惑,因为它清楚地实现了接口(interface)。如何解决此错误?

最佳答案

传递一个指向缓冲区的指针,而不是缓冲区本身:

import "bufio"
import "bytes"

func main() {
    var b bytes.Buffer
    foo := bufio.NewWriter(&b)
}

关于go - 收到 "bytes.Buffer does not implement io.Writer"错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23454940/

相关文章:

将 slice 限制为最大元素

docker - 使用 docker & go cli 将文件从我的本地机器上传到 Api 服务器

go - 为什么我的包中的功能不起作用

遵循 Pluralsight Go 教程时出现无效内存地址错误

winapi - 如何正确调用 netapi32!NetSessionEnum()?

testing - Go 测试覆盖率中的 covered 和 not tracked 是什么意思?

Golang YAML 使用 map 读取

html - Go - 从具有已知结构的文档中获取单个特定 HTML 元素的文本

postgresql - 在 Postgresql 数据库中存储递归结构

go - 初始化常量变量