go – reading binary file with struct

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

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

有人能告诉我为什么吗?

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

谢谢 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

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 go – reading binary file with struct

答案1

得分: 6

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

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
}

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:

确定