SoFunction
Updated on 2025-03-05

Golang uses gob to implement the serialization process of structures in detail

Golang has its own serialization format called gob. Use gob to encode and decode structures. You can use other formats, such as JSON, XML, protobuff, etc. The specific selection should be based on actual needs, but when both receiving and sending are Golang, I suggest using Go's gob format.

Introduction to Gob

gob is in the kg/encoding/gob package:

  • The gob stream is self-described, which means we don't need to create separate files to interpret (using protobuff format requires creating files)
  • Each data item in the gob stream has its type description before (some predefined types)

The Gob package is simple, including only 8 functions and 5 types:

func Register(value interface{})
func RegisterName(name string, value interface{})
type CommonType
type Decoder
func NewDecoder(r ) *Decoder
func (dec *Decoder) Decode(e interface{}) error
func (dec *Decoder) DecodeValue(v ) error
type Encoder
func NewEncoder(w ) *Encoder
func (enc *Encoder) Encode(e interface{}) error
func (enc *Encoder) EncodeValue(value ) error
type GobDecoder
type GobEncoder

Single object serialization

First define the student structure, including two fields Name and Age.

Use and methods, receive and objects, for reading and writing files:

package main
import (
       "fmt"
       "os"
       "encoding/gob"
)
type Student struct {
       Name string
       Age int32
}
func main() {
       ("Gob Example")
       student := Student{"Ketan Parmar",35}
       err := writeGob("./",student)
       if err != nil{
              (err)
       }
       var studentRead = new (Student)
       err = readGob("./",studentRead)
       if err != nil {
              (err)
       } else {
              (, "\t", )
       }
}
func writeGob(filePath string,object interface{}) error {
       file, err := (filePath)
       if err == nil {
              encoder := (file)
              (object)
       }
       ()
       return err
}
func readGob(filePath string,object interface{}) error {
       file, err := (filePath)
       if err == nil {
              decoder := (file)
              err = (object)
       }
       ()
       return err
}

List data serialization

First create an array or slice of student structure and then fill in the data. The following example does not require modifying the readGob and writeGob functions:

package main
import (
       "fmt"
       "os"
       "encoding/gob"
)
type Student struct {
       Name string
       Age int32
}
type Students []Student
func main() {
       ("Gob Example")
       students := Students{}
       students = append(students,Student{"Student 1",20})
       students = append(students,Student{"Student 2",25})
       students = append(students,Student{"Student 3",30})
       err := writeGob("./",students)
       if err != nil{
              (err)
       }
       var studentRead = new (Students)
       err = readGob("./",studentRead)
       if err != nil {
              (err)
       } else {
              for _,v := range *studentRead{
                     (, "\t", )
              }
       }
}

The above two examples mainly use NewEncoder and NewDecoder. Let’s take a look at other functions: Register, Encode, EncodeValue, Decode and DecodeValue.

Encode and Decode functions are mainly used in web applications, and the method signature is as follows:

func (dec *Decoder) Decode(e interface{}) error
func (enc *Encoder) Encode(e interface{}) error

Simple encoding example

package main
import (
   "fmt"
   "encoding/gob"
   "bytes"
)
type Student struct {
   Name string
   Age int32
}
func main() {
   ("Gob Example")
   studentEncode := Student{Name:"Ketan",Age:30}
   var b 
   e := (&b)
   if err := (studentEncode); err != nil {
      panic(err)
   }
   ("Encoded Struct ", b)
   var studentDecode Student
   d := (&b)
   if err := (&studentDecode); err != nil {
      panic(err)
   }
   ("Decoded Struct ", ,"\t",)
}

The above example serializes and deserializes the student structure. After serialization, it is stored in the byte buffer variable b, and can be transmitted on the network using b first. To decode, you only need to create the same structural object and provide its address. The studentDecode variable gets the decoded content.

Encoding is used in TCP connections

TCP client: Open the connection and use method to encode the data for transmission:

package main
import (
   "fmt"
   "encoding/gob"
   "net"
   "log"
)
type Student struct {
   Name string
   Age int32
}
func main() {
   ("Client")
   //create structure object
    studentEncode := Student{Name:"Ketan",Age:30}
   ("start client");
   // dial TCP connection
   conn, err := ("tcp", "localhost:8080")
   if err != nil {
      ("Connection error", err)
   }
   //Create encoder object, We are passing connection object in Encoder
   encoder := (conn)
   // Encode Structure, IT will pass student object over TCP connection
   (studentEncode)
   // close connection
   ()
   ("done");
}

TCP Server: Listen to port 8080, handles all clients in the go coroutine, decodes the student structure and outputs:

package main
import (
   "fmt"
   "net"
   "encoding/gob"
)
type Student struct {
   Name string
   Age int32
}
func handleConnection(conn ) {
   // create new decoder object and provide connection
   dec := (conn)
   // create blank student object
   p := &Student{}
   // decode serialize data
   (p)
   // print
   ("Hello ",,", Your Age is ",);
   // close connection for that client
   ()
}
func main() {
   ("Server")
   // start TCP server and listen on port 8080
   ln, err := ("tcp", ":8080")
   if err != nil {
      // handle error
      panic(err)
   }
   for {
      // this blocks until connection or error
      conn, err := ()
      if err != nil {
         // handle error
         continue
      }
      // a goroutine handles conn so that the loop can accept other connections
      go handleConnection(conn)
   }
}

There is no serialization implemented above, this article gives the golang-ttl-map implementation:

func (h *Heap) append(data Data) (err error) {
	()
	defer ()
       // Open the file	var file *
	file, err = (, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
	if err != nil {
		return
	}
	defer func() {
		_ = ()
	}()
	defer func() {
		_ = ()
	}()
       // Define the buffer	var buf 
	enc := (&buf)
       // Serialization	err = (data)
	if err != nil {
		return
	}
	bs := ()
	bs = append(bs, '\n')
       // Write to the file	_, err = (bs)
	if err != nil {
		return
	}
	return
}

This is the introduction to this article about Golang's detailed explanation of the serialization process of using gob to implement the structure. For more relevant content on Golang's structure serialization, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!