英文:
go - reading binary file with struct
问题
我正在尝试使用Go语言读取二进制文件,但有一个问题。
如果我按照以下方式读取,一切都正常:
package main
import (
"encoding/binary"
"fmt"
"os"
)
type Header struct {
str1 int32
str2 [255]byte
str3 float64
}
func main() {
path := "test.BIN"
file, _ := os.Open(path)
defer file.Close()
thing := Header{}
binary.Read(file, binary.LittleEndian, &thing.str1)
binary.Read(file, binary.LittleEndian, &thing.str2)
binary.Read(file, binary.LittleEndian, &thing.str3)
fmt.Println(thing)
}
但如果我将.Read
部分优化为:
binary.Read(file, binary.LittleEndian, &thing)
//binary.Read(file, binary.LittleEndian, &thing.str1)
//binary.Read(file, binary.LittleEndian, &thing.str2)
//binary.Read(file, binary.LittleEndian, &thing.str3)
我会得到以下错误:
panic: reflect: reflect.Value.SetInt using value obtained using unexported field
有人能告诉我为什么吗?
所有的示例都使用了"优化方式"。
谢谢
英文:
I'm trying to reading binary files with golang, but have a question.
If I read it this way, all will be fine
package main
import (
"encoding/binary"
"fmt"
"os"
)
type Header struct {
str1 int32
str2 [255]byte
str3 float64
}
func main() {
path := "test.BIN"
file, _ := os.Open(path)
defer file.Close()
thing := Header{}
binary.Read(file, binary.LittleEndian, &thing.str1)
binary.Read(file, binary.LittleEndian, &thing.str2)
binary.Read(file, binary.LittleEndian, &thing.str3)
fmt.Println(thing)
}
But if I optimize the .Read-Section to
binary.Read(file, binary.LittleEndian, &thing)
//binary.Read(file, binary.LittleEndian, &thing.str1)
//binary.Read(file, binary.LittleEndian, &thing.str2)
//binary.Read(file, binary.LittleEndian, &thing.str3)
I get the following error:
panic: reflect: reflect.Value.SetInt using value obtained using unexported field
Could anybody say me why?
All examples are useing the "optimized-way"
Thanks
答案1
得分: 6
str1
、str2
和str3
是未导出的。这意味着其他包无法访问它们。要导出它们,将首字母大写。
type Header struct {
Str1 int32
Str2 [255]byte
Str3 float64
}
英文:
str1
, str2
, and str3
are unexported. That means other packages can't see them. To export them, capitalize the first letter.
type Header struct {
Str1 int32
Str2 [255]byte
Str3 float64
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论