strings.Reader将目标缓冲区留空。

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

*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)
}

当我运行调试器并查看method2reader的值时,我发现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)
}

huangapple
  • 本文由 发表于 2022年8月11日 10:38:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/73314680.html
匿名

发表评论

匿名网友

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

确定