Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Go, how can I convert a struct to a byte array?

I have an instance of a struct that I defined and I would like to convert it to an array of bytes. I tried []byte(my_struct), but that did not work. Also, I was pointed to the binary package, but I am not sure which function I should use and how I should use it. An example would be greatly appreciated.

like image 851
abw333 Avatar asked May 02 '13 04:05

abw333


People also ask

How do I assign a byte array in Golang?

To convert String to Byte array in Golang, use the byte() function. A byte is an 8-bit unsigned int. The byte() function takes a string as an input and returns the array.

What is a [] byte in Golang?

The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).


Video Answer


2 Answers

One possible solution is the "encoding/gob" standard package. The gob package creates an encoder/decoder that can encode any struct into an array of bytes and then decode that array back into a struct. There's a great post, here.

As others have pointed out, it's necessary to use a package like this because structs, by their nature, have unknown sizes and cannot be converted into arrays of bytes.

I've included some code and a play.

package main  import (     "bytes"     "encoding/gob"     "fmt"     "log" )  type P struct {     X, Y, Z int     Name    string }  type Q struct {     X, Y *int32     Name string }  func main() {     // Initialize the encoder and decoder.  Normally enc and dec would be     // bound to network connections and the encoder and decoder would     // run in different processes.     var network bytes.Buffer        // Stand-in for a network connection     enc := gob.NewEncoder(&network) // Will write to network.     dec := gob.NewDecoder(&network) // Will read from network.     // Encode (send) the value.     err := enc.Encode(P{3, 4, 5, "Pythagoras"})     if err != nil {         log.Fatal("encode error:", err)     }      // HERE ARE YOUR BYTES!!!!     fmt.Println(network.Bytes())      // Decode (receive) the value.     var q Q     err = dec.Decode(&q)     if err != nil {         log.Fatal("decode error:", err)     }     fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y) } 
like image 128
Adam Avatar answered Sep 17 '22 12:09

Adam


I assume you want something like the way C handles this. There is no built in way to do that. You will have to define your own serialization and deserialization to and from bytes for your struct. The binary package will help you encode the fields in your struct to bytes that you can add to the byte array but you will be responsible for specifying the lengths and offsets in the byte array that will hold the fields from your struct.

Your other options are to use one of the encoding packages: http://golang.org/pkg/encoding/ such as gob or json.

EDIT:

Since you want this for making a hash as you say in your comment the easisest thing to do is use []byte(fmt.Sprintf("%v", struct)) like so: http://play.golang.org/p/yY8mSdZ_kf

like image 21
Jeremy Wall Avatar answered Sep 16 '22 12:09

Jeremy Wall