gpt4 book ai didi

go - 在 Golang 中连续运行 io.Copy(os.Stdout, &r) 结果不同

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:56 27 4
gpt4 key购买 nike

我在玩 Golang。关于 io.Copy我在代码中放置了 2 个连续的 io.Copy,但我希望它输出两次结果(testtesttest)。但是第二个是零。谁能帮忙解释一下为什么?谢谢

package main

import (
"io"
"os"
"strings"
"fmt"

)

type testReader struct {
w io.Reader
str string

}


func (tt *testReader) Read (b []byte) (n int, err error) {


io.Copy(os.Stdout, tt.w)
n, err = tt.w.Read(b)
if tt.w !=nil {
return 0,io.EOF
}
return
}

func main() {
s := strings.NewReader("testtesttest!!!")
r := testReader{s,"ttthhh"}
fmt.Println(&r)
io.Copy(os.Stdout, &r)
// s.Seek(0,0) // solution from Poy's answer
io.Copy(os.Stdout, &r)

}

最佳答案

我要删减给定的示例(因为有一点噪音):

package main

import (
"io"
"os"
"strings"
)

func main() {
s := strings.NewReader("testtesttest")
io.Copy(os.Stdout, s) // Will print "testtesttest"
io.Copy(os.Stdout, s) // Won't print anything
}

第二个副本不会输出任何内容的原因是 io.Reader (s) 已被读取。从 io.Reader 读取不是幂等的(您不能调用它两次来获得相同的结果)。 它也没有办法“重置”它或任何东西。

正如@JRLambert 指出的那样,您有 s.Seek()s.Reset()让您重新开始阅读。

关于go - 在 Golang 中连续运行 io.Copy(os.Stdout, &r) 结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53366810/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com