[Go语言]为什么bufio.Reader替代了strings.Reader?

huangapple go评论78阅读模式
英文:

[Golang ]why bufio reader change the strings reader?

问题

代码如下:

s := strings.NewReader("ABCDEFGJHIJK")
fmt.Printf("pa is %d\n", s.GetValueI()) //GetValueI()返回r.i的值

br := bufio.NewReader(s)
fmt.Printf("papa is %d\n", s.GetValueI())

cc, _ := br.ReadByte()
fmt.Printf("%c\n", cc)
fmt.Printf("papapa is %d\n", s.GetValueI())

输出结果为:

pa is 0
papa is 0
A
papapa is 12

所以结果很奇怪...
为什么在调用bufio的ReadByte()方法时,papapa的值为12?
这真的让我很困惑...

英文:

The code follows ==

s := strings.NewReader("ABCDEFGJHIJK")
fmt.Printf("pa is %d\n ", s.GetValueI()) //GetValueI() returns the value of r.i

br := bufio.NewReader(s)
fmt.Printf("papa is %d\n ", s.GetValueI())

cc, _ := br.ReadByte()
fmt.Printf("%c\n", cc)
fmt.Printf("papapa is %d\n ", s.GetValueI())

The prints shows:
pa is 0
papa is 0
A
papapa is 12

So weired Results..
why papapa is 12 when bufio call ReadByte() ?
It really confuse me a lot ..

答案1

得分: 2

缓冲读取器的作用是更高效地读取数据流,无论请求的读取大小是多少。

当调用ReadByte时,如果内部缓冲区为空,它会调用内部的fill()方法来重新填充缓冲区,在这种情况下会消耗整个strings.Reader。然后从这个内部缓冲区返回单个字节。

英文:

The point of a buffered reader is to read the data stream more efficiently, no matter what size reads are requested.

When you call ReadByte, if the internal buffer is empty, it calls its internal fill() method to refill the buffer, which in this case consumes the entire strings.Reader. The single byte is then returned from this internal buffer.

huangapple
  • 本文由 发表于 2015年12月24日 21:42:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/34453727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定