bufio.Buffered 返回 0 一个未解决 bug

244 天前
 zzzkkk

最近再练手精进 网上弄了段代码 运行发型 bufio.Buffered()永远返回 0

package main

import (
        "bufio"
        "fmt"
        "strings"
)

func main() {
        //原始字符串
        str := "12345678901234567890123456789012345678901234567890"

        //将字符串转换为流式 I/O 对象
        strReader := strings.NewReader(str)

        //设置读缓存区大小
        bufReader := bufio.NewReaderSize(strReader, 16) //16byte

        //缓存读
        p := make([]byte, 4)
        n, err := bufReader.Read(p)
        if err != nil {
                panic(err)
        }

        buffered := bufReader.Buffered()
        fmt.Printf("buffered:%d, content:%s\n", buffered, p[:n])
}

网上搜来搜去只返回一个结果

13 年前有人 report 过 4 年前也有人遇到过 到现在是不是还没解决?

https://groups.google.com/g/golang-nuts/c/1smBsPOdFT0

I'm having a similar problem as the original poster. I expect Buffered() to return the number of bytes that can be read from the current buffer, like the documentation states. However a call to Buffered() returns 0 both before and after a call to any Read() that finds bytes in the buffer. In my case the Reader is a net.Conn.

How do we use Buffered() properly? This is the only google result I could find that even mentions using the function.

I ended up solving my problem without using bufio. -Sam

990 次点击
所在节点    Go 编程语言
7 条回复
klesh
244 天前
啥版本?似乎 v1.20+ 没这个问题 https://go.dev/play/p/0Iqldy6RqNY?v=goprev
darrh00
244 天前
输出:buffered:12, content:1234

不是 12 吗,哪是 0 ?
Jooeeee
244 天前
试着跑了一下:
buffered:12, content:1234
ranleng
244 天前
❯ go version
go version go1.20.6 darwin/arm64
❯ go run main.go
buffered:12, content:1234
lxcForPHP
244 天前
go 1.18 输出: buffered:12, content:1234
dif
243 天前
和楼上一样:
go version
warning: GOPATH set to GOROOT (D:\devtools\go) has no effect
go version go1.19.5 windows/amd64

buffered:12 ,context:1234
dif
243 天前
所以,建议这种问题先把版本号发出来

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/972407

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX