Home > Software design >  How to read a binary file into a struct and reflection - Go Language
How to read a binary file into a struct and reflection - Go Language

Time:03-30

I am trying to write a program to read a binary file into a struct in golang, the approach is to use the binary package to read a binary file to populate a struct that contains arrays, I am using arrays and not slices because I want to specify the field length, this seems to work fine but when I try to use reflection to print our the values of the fields I am getting this error

panic: reflect: call of reflect.Value.Bytes on array Value

Here is the code

package main

import (
    "encoding/binary"
    "fmt"
    "log"
    "os"
    "reflect"
)

type SomeStruct struct {
    Field1                     [4]byte
    Field2                  [2]byte
    Field3                [1]byte

}

func main() {
    f, err := os.Open("/Users/user/Downloads/file.bin")
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()

    s := SomeStruct{}
    err = binary.Read(f, binary.LittleEndian, &s)

    numOfFields := reflect.TypeOf(s).NumField()
    ps := reflect.ValueOf(&s).Elem()

    for i := 0; i < numOfFields; i   {
        value := ps.Field(i).Bytes()
        for j := 0; j < len(value); j   {
            fmt.Print(value[j])
        }
    }
}

when I change the code to this

package main

import (
    "encoding/binary"
    "fmt"
    "log"
    "os"
    "reflect"
)

type SomeStruct struct {
    Field1 [4]byte
    Field2 [2]byte
    Field3 [1]byte
}

func main() {
    f, err := os.Open("/Users/user/Downloads/file.bin")
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()

    s := SomeStruct{}
    err = binary.Read(f, binary.LittleEndian, &s)

    numOfFields := reflect.TypeOf(s).NumField()
    ps := reflect.ValueOf(&s).Elem()

    for i := 0; i < numOfFields; i   {
        value := ps.Field(i)
        fmt.Print(value)

    }
}


it prints the arrays with their ascii representation, I need to print the char representation of the ascii and that when I get the panic

thoughts?

CodePudding user response:

The Bytes documentation says:

Bytes returns v's underlying value. It panics if v's underlying value is not a slice of bytes.

Slice the array to get a slice of bytes:

field := ps.Field(i)
value := field.Slice(0, field.Len()).Bytes()
for j := 0; j < len(value); j   {
    fmt.Print(value[j])
}

You can also iterate through the array:

value := ps.Field(i)
for j := 0; j < value.Len(); j   {
    fmt.Print(byte(value.Index(j).Uint()))
}
  • Related