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 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面