Link Search Menu Expand Document

Serializing objects to binary format

  • Besides the well-known JSON and XML, Go also offers the binary format, gob. This recipe goes through the basic concept of how to use the gob package.

Create the gob.go file with the following content:

package main

import (

type User struct {
	FirstName string
	LastName  string
	Age       int
	Active    bool

func (u User) String() string {
	return fmt.Sprintf(`{"FirstName":%s,"LastName":%s,
											 "Age":%d,"Active":%v }`,
		u.FirstName, u.LastName, u.Age, u.Active)

type SimpleUser struct {
	FirstName string
	LastName  string

func (u SimpleUser) String() string {
	return fmt.Sprintf(`{"FirstName":%s,"LastName":%s}`,
		u.FirstName, u.LastName)

func main() {

	var buff bytes.Buffer

	// Encode value
	enc := gob.NewEncoder(&buff)
	user := User{
	fmt.Printf("%X\n", buff.Bytes())

	// Decode value
	out := User{}
	dec := gob.NewDecoder(&buff)

	out2 := SimpleUser{}



sangam:golang-daily sangam$ go run gob.go
										 "Age":24,"Active":true }
sangam:golang-daily sangam$ 

How it works…

  • The gob serialization and deserialization need the Encoder and Decoder. The gob.NewEncoder function creates the Encoder with the underlying Writer.
  • Each call of the Encode method will serialize the object into a gob format. The gob format itself is the self-describing binary format. This means each serialized struct is preceded by its description.

  • To decode the data from the serialized form, the Decoder must be created by calling the gob.NewDecoder with the underlying Reader. The Decode then accepts the pointer to the structure where the data should be deserialized.