Created
March 14, 2025 17:22
-
-
Save Integralist/620ec233247a6eff8061e38be53ada46 to your computer and use it in GitHub Desktop.
Serialize and Deserialize Go types using gob #go #golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package gob manages streams of gobs - binary values exchanged between an Encoder | |
// (transmitter) and a Decoder (receiver). | |
package main | |
import ( | |
"bytes" | |
"encoding/gob" | |
"fmt" | |
"log" | |
) | |
type Person struct { | |
Name string | |
Age int | |
Address Address | |
} | |
type Address struct { | |
Street string | |
City string | |
} | |
func main() { | |
// Original Person object | |
originalPerson := Person{ | |
Name: "Alice", | |
Age: 30, | |
Address: Address{ | |
Street: "123 Main St", | |
City: "Anytown", | |
}, | |
} | |
// 1. Serialization (Gob Encoding) | |
var buf bytes.Buffer | |
enc := gob.NewEncoder(&buf) | |
err := enc.Encode(originalPerson) | |
if err != nil { | |
log.Fatalf("Gob encode error: %v", err) | |
} | |
// 2. Deserialization (Gob Decoding) | |
var decodedPerson Person | |
dec := gob.NewDecoder(&buf) | |
err = dec.Decode(&decodedPerson) | |
if err != nil { | |
log.Fatalf("Gob decode error: %v", err) | |
} | |
// Verify the decoded object | |
fmt.Printf("Original Person: %+v\n", originalPerson) | |
fmt.Printf("Decoded Person: %+v\n", decodedPerson) | |
//Check that the two objects are identical | |
if originalPerson == decodedPerson { | |
fmt.Println("The objects are identical.") | |
} else { | |
fmt.Println("The objects are different.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment