我是 golang 的新手,当我阅读包“archtive/tar”的代码示例时,我读到了这样的代码:
// Iterate through the files in the archive.
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
log.Fatalln(err)
}
fmt.Printf("Contents of %s:\n", hdr.Name)
if _, err := io.Copy(os.Stdout, tr); err != nil {
log.Fatalln(err)
}
fmt.Println()
}
输出就像这样:
Contents of readme.txt:
This archive contains some text files.
Contents of gopher.txt:
Gopher names:
George
Geoffrey
Gonzo
Contents of todo.txt:
Get animal handling license.
谁能告诉我程序是如何打印结构体的?谢谢。
最佳答案
您遗漏了示例中的重要部分,即您发布的内容之前的两行。
// Open the tar archive for reading.
r := bytes.NewReader(buf.Bytes())
tr := tar.NewReader(r)
这将创建一个 tar.Reader
,它实现了 io.Reader
。 if
语句中的语句io.Copy(os.Stdout, tr)
知道如何将读取器的内容复制到Stdout
。
注意包文档中的代码示例不会将它创建的 tar 写入磁盘也可能很有用。这一切都是在内存中使用 bytes.Buffer
完成的。写入磁盘的示例在 io
包中。
关于go - 无法理解有关 go 打印功能的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47290361/