go – reading binary file with struct

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

go - reading binary file with struct

问题

我正在尝试使用Go语言读取二进制文件,但有一个问题。

如果我按照以下方式读取,一切都正常:

  1. package main
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "os"
  6. )
  7. type Header struct {
  8. str1 int32
  9. str2 [255]byte
  10. str3 float64
  11. }
  12. func main() {
  13. path := "test.BIN"
  14. file, _ := os.Open(path)
  15. defer file.Close()
  16. thing := Header{}
  17. binary.Read(file, binary.LittleEndian, &thing.str1)
  18. binary.Read(file, binary.LittleEndian, &thing.str2)
  19. binary.Read(file, binary.LittleEndian, &thing.str3)
  20. fmt.Println(thing)
  21. }

但如果我将.Read部分优化为:

  1. binary.Read(file, binary.LittleEndian, &thing)
  2. //binary.Read(file, binary.LittleEndian, &thing.str1)
  3. //binary.Read(file, binary.LittleEndian, &thing.str2)
  4. //binary.Read(file, binary.LittleEndian, &thing.str3)

我会得到以下错误:

panic: reflect: reflect.Value.SetInt using value obtained using unexported field

有人能告诉我为什么吗?

所有的示例都使用了"优化方式"。

谢谢 go – reading binary file with struct

英文:

I'm trying to reading binary files with golang, but have a question.

If I read it this way, all will be fine

  1. package main
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "os"
  6. )
  7. type Header struct {
  8. str1 int32
  9. str2 [255]byte
  10. str3 float64
  11. }
  12. func main() {
  13. path := "test.BIN"
  14. file, _ := os.Open(path)
  15. defer file.Close()
  16. thing := Header{}
  17. binary.Read(file, binary.LittleEndian, &thing.str1)
  18. binary.Read(file, binary.LittleEndian, &thing.str2)
  19. binary.Read(file, binary.LittleEndian, &thing.str3)
  20. fmt.Println(thing)
  21. }

But if I optimize the .Read-Section to

  1. binary.Read(file, binary.LittleEndian, &thing)
  2. //binary.Read(file, binary.LittleEndian, &thing.str1)
  3. //binary.Read(file, binary.LittleEndian, &thing.str2)
  4. //binary.Read(file, binary.LittleEndian, &thing.str3)

I get the following error:

  1. panic: reflect: reflect.Value.SetInt using value obtained using unexported field

Could anybody say me why?

All examples are useing the "optimized-way"

Thanks go – reading binary file with struct

答案1

得分: 6

str1str2str3是未导出的。这意味着其他包无法访问它们。要导出它们,将首字母大写。

  1. type Header struct {
  2. Str1 int32
  3. Str2 [255]byte
  4. Str3 float64
  5. }
英文:

str1, str2, and str3 are unexported. That means other packages can't see them. To export them, capitalize the first letter.

  1. type Header struct {
  2. Str1 int32
  3. Str2 [255]byte
  4. Str3 float64
  5. }

huangapple
  • 本文由 发表于 2017年2月26日 07:27:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/42462869.html
匿名

发表评论

匿名网友

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

确定