6

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 Answer 1

7

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you :) now i know the (un)exported message :) )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.