overboarded
overboarded

Reputation: 83

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 :)

Upvotes: 6

Views: 10946

Answers (1)

MahlerFive
MahlerFive

Reputation: 5299

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
}

Upvotes: 7

Related Questions