英文:
*strings.Reader leaving target buffer blank
问题
我正在尝试将一个*strings.Reader
从一个函数传递给另一个函数。读者的内容是"Foo"
。这是创建/传递读者的代码:
_, err = funcNum2(strings.NewReader("Foo"))
...以及从中读取的代码...
buf := []byte{}
_, err := reader.Read(buf)
if err != nil {
fmt.Printf("从读者中读取错误:%v\n", err)
}
当我运行调试器并查看method2
中reader
的值时,我发现reader
仍然包含"Foo"
。然而,为什么当我尝试读取到buf
时,buf
是空的,请帮助我理解这个问题。
英文:
I am attempting to pass an *strings.Reader
from one function to another. The content of the reader is "Foo"
. This is the code that creates/passes the reader:
_, err = funcNum2(strings.NewReader("Foo"))
... and the code that reads from it...
buf := []byte{}
_, err := reader.Read(buf)
if err != nil {
fmt.Printf("Error reading from reader: %v\n", err)
}
When I run the debugger and look at the value of reader
in method2
, I find that reader
still contains "Foo"
. However, can you please help me understand why, when I try to read into buf
, buf
is empty?
答案1
得分: 0
当分配buf:=[]byte{}
时,分配了一个大小为0的字节切片。为了从缓冲区读取,您可以获取读取器的缓冲区大小reader.Size()
,创建一个相同大小的字节切片,并将数据写入其中。
以下代码可以工作:
package main
import (
"fmt"
"strings"
)
func print_reader(read *strings.Reader) {
buf := make([]byte, read.Size()) //在这里使用read.Size()
n, err := read.Read(buf)
fmt.Println(n, err, string(buf), read.Size())
}
func main() {
rd := strings.NewReader("test")
print_reader(rd)
}
希望对您有所帮助!
英文:
when assigning buf:=[]byte{}
, a byte slice of size 0 is assigned. In order to read from buffer you can take size of the reader's buffer, reader.Size()
, create a byte slice of that size. Write to it.
following code works
package main
import (
"fmt"
"strings"
)
func print_reader(read *strings.Reader) {
buf := make([]byte, 4) //give read.Size() here
n, err := read.Read(buf)
fmt.Println(n, err, string(buf), read.Size())
}
func main() {
rd := strings.NewReader("test")
print_reader(rd)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论