type Person struct { Name string Age int Emails []string } func main() { person := Person{ Name: "John Smith", Age: 25, Emails: []string{"[email protected]", "[email protected]"}, } var buffer bytes.Buffer encoder := gob.NewEncoder(&buffer) err := encoder.Encode(person) if err != nil { log.Fatal(err) } fmt.Println(buffer.Bytes()) }
func main() { data := []byte{ 0x0, 0x0, 0x0, 0x3b, 0x5, 0x50, 0x65, 0x72, 0x73, 0x6f, 0x6e, 0x12, 0x0, 0x3, 0x4a, 0x6f, 0x68, 0x6e, 0x20, 0x53, 0x6d, 0x69, 0x74, 0x68, 0xa, 0x0, 0x2, 0x0, 0x7, 0x6a, 0x6f, 0x68, 0x6e, 0x40, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2b, 0x0, 0x12, 0x6a, 0x6f, 0x68, 0x6e, 0x2e, 0x73, 0x6d, 0x69, 0x74, 0x68, 0x40, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, } var person Person decoder := gob.NewDecoder(bytes.NewReader(data)) err := decoder.Decode(&person) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", person) }This example shows how to decode a byte slice containing gob-encoded data into a Person struct. The gob.NewDecoder function creates a new decoder instance that reads from a byte reader. The decoder.Decode method reads the encoded data from the byte reader and stores it in the person variable. The encoding/gob package is part of the Go standard library, which means it is distributed with Go itself.