Arj
Arj

Reputation: 2046

Unable to decode byte slice back into struct

I am trying to read a byte array and output it into a struct in Go. The official example is a good starting point, but this only decodes a single float64. This other snippet shows that it definitely can be done with structs.

My play, however, fails with binary.Read: invalid type ... .

I thought this was to do with the Read function accepting only fixed-length data to read into:

binary.Read reads structured binary data from r into data. Data must be a pointer to a fixed-size value or a slice of fixed-size values

This is why my struct definition contains only fixed-length data.

I can't see that I'm doing anything vastly different to the working examples, and the error code isn't much help beyond the length issue - any ideas?

Upvotes: 0

Views: 793

Answers (1)

Alexander Trakhimenok
Alexander Trakhimenok

Reputation: 6278

You have problems with you struct that it has unexported fields.

Here is the working code:

https://play.golang.org/p/LHTeF-_2lX

package main

import (
    "fmt"
    "bytes"
    "encoding/binary"
    "net"
)

type myEvent struct {
    IP_version int32
    Ipv6_src_addr [16]byte
}


func readFromByteArrayIntoStruct() {

    // create event
    ip := net.ParseIP("2001::face")
    var ipBytes [16]byte;
    copy(ipBytes[:], ip.To16())
    event := myEvent {
        IP_version: 4, 
        Ipv6_src_addr: ipBytes,
    }

    // convert to bytes
    buf := new(bytes.Buffer)
    if err := binary.Write(buf, binary.BigEndian, event); err != nil {
        fmt.Println("binary.Write failed:", err)
        return
    }
    eventBytes := buf.Bytes()
    fmt.Println(buf.Len(), eventBytes)

    // read back the bytes into a new event
    reader := bytes.NewReader(eventBytes)
    var decodedEvent myEvent 

    if err := binary.Read(reader, binary.BigEndian, &decodedEvent); err != nil {
        fmt.Println("binary.Read failed:", err)
    } else {
        fmt.Printf("decodedEvent: %+v", decodedEvent)
    }
}

func main() {
    readFromByteArrayIntoStruct()
}

Upvotes: 2

Related Questions