英文:
[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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论