« Back to Index

Go: Serialize and Deserialize types using gob

View original Gist on GitHub

Tags: #go #serialization

main.go

// 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.")
	}
}