dq13733519262
dq13733519262
2017-02-25 23:27
采纳率: 0%
浏览 120
已采纳

go-使用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 :)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douqin7086
    douqin7086 2017-02-25 23:33
    已采纳

    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
    }
    
    点赞 评论

相关推荐