最近再练手精进 网上弄了段代码 运行发型 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
1
klesh 2023-09-10 10:27:09 +08:00
啥版本?似乎 v1.20+ 没这个问题 https://go.dev/play/p/0Iqldy6RqNY?v=goprev
|
2
darrh00 2023-09-10 10:32:24 +08:00
输出:buffered:12, content:1234
不是 12 吗,哪是 0 ? |
3
Jooeeee 2023-09-10 10:32:44 +08:00
试着跑了一下:
buffered:12, content:1234 |
4
ranleng 2023-09-10 12:00:19 +08:00
❯ go version
go version go1.20.6 darwin/arm64 ❯ go run main.go buffered:12, content:1234 |
5
lxcForPHP 2023-09-10 16:10:48 +08:00
go 1.18 输出: buffered:12, content:1234
|
6
dif 2023-09-11 11:24:36 +08:00
和楼上一样:
go version warning: GOPATH set to GOROOT (D:\devtools\go) has no effect go version go1.19.5 windows/amd64 buffered:12 ,context:1234 |
7
dif 2023-09-11 11:25:08 +08:00
所以,建议这种问题先把版本号发出来
|