dongzhuo3376 2017-11-14 16:12
浏览 32
已采纳

无法理解有关go的打印功能的代码

i am new to golang, when i read the code example of package "archtive/tar",i read some code like this:

// 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:
", hdr.Name)
    if _, err := io.Copy(os.Stdout, tr); err != nil {
        log.Fatalln(err)
    }
    fmt.Println()
}

the output just like this:

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.

can anyone tell me how the programe print the body of the struct? thank you.

  • 写回答

1条回答 默认 最新

  • dongzongxun8491 2017-11-14 16:22
    关注

    You left out a vital piece of the example, the two lines preceding what you posted.

    // Open the tar archive for reading.
    r := bytes.NewReader(buf.Bytes())
    tr := tar.NewReader(r)
    

    This creates a tar.Reader which implements io.Reader. The statement io.Copy(os.Stdout, tr) in the if statement knows how to copy the contents of the reader to Stdout.

    Godoc for tar.Reader

    Also might be useful to note that the code example in the package documentation doesn't ever write the tar it creates to disk. It is all done in memory using bytes.Buffers. Examples of writing to disk would be in the io package.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作