How do I dump structs into byte arrays without reflection?
You may have already encountered the encoding/binary package, but it relies on the reflect package, which poses an issue when dealing with structs with uncapitalized (unexported) fields.
Alternative Solution: Leveraging the gob Package
To circumvent this limitation, consider utilizing the gob package. By implementing the GobDecoder and GobEncoder interfaces, you can serialize and deserialize private fields safely and efficiently. This approach is platform-independent and only requires adding those functions to structs with unexported fields, leaving the rest of your code clean.
Implementation Example
Here's how you can implement the GobEncode and GobDecode methods:
func (d *Data) GobEncode() ([]byte, error) { w := new(bytes.Buffer) encoder := gob.NewEncoder(w) err := encoder.Encode(d.id) if err != nil { return nil, err } err = encoder.Encode(d.name) if err != nil { return nil, err } return w.Bytes(), nil } func (d *Data) GobDecode(buf []byte) error { r := bytes.NewBuffer(buf) decoder := gob.NewDecoder(r) err := decoder.Decode(&d.id) if err != nil { return err } return decoder.Decode(&d.name) }
In your main function, you can write and read the struct using the gob package:
func main() { d := Data{id: 7} copy(d.name[:], []byte("tree")) buffer := new(bytes.Buffer) // writing enc := gob.NewEncoder(buffer) err := enc.Encode(d) if err != nil { log.Fatal("encode error:", err) } // reading buffer = bytes.NewBuffer(buffer.Bytes()) e := new(Data) dec := gob.NewDecoder(buffer) err = dec.Decode(e) fmt.Println(e, err) }
The above is the detailed content of How to Serialize Structs with Unexported Fields into Byte Arrays in Go without Reflection?. For more information, please follow other related articles on the PHP Chinese website!