Golang: Serialize struct using gob- Part 1

By Ketan Parmar Go Language No Comments on Golang: Serialize struct using gob- Part 1

Serialize of the struct will help you to transfer data over network or it will help you to write data on disk. In a distributed system you generate data then serialize, compress and send. On other end you receive data then decompress, deserialize and process. The entire process must be fast and efficient. Go lang has it’s own serialize format called gob. Using gob you can encode and decode structure. You can use other formats like JSON, XML, protobuff, capnproto, etc.. You should choose a format or protocol based on your requirement. I suggest to use Go’s gob format when you have sender and receiver both are developed in Go lang.

Package: pkg/encoding/gob

  1. Stream of gob is self describing, It means we don’t need to create separate file to explain, like we need to create file in protobuff
  2. Each data item in the stream is preceded by a specification of its type, expressed in terms of a small set of predefined types.

Gob is very simple package from out side. It has only 8 functions and 5 types.

Example 1

In this simple example, We have student structure. It has two fields Name and Age. We have used method gob.NewEncoder and gob.NewDecoder both methods accepts io.Writer and io.Reader object. These methods use to write and read gob file.

Example 2

Let’s create array / slice of student structure and fill some data. For following example we do not need to change readGob and writeGob functions.

In this article, I have explored NewEncoder and NewDecoder functions. In next article, I will explore other functions like Register, Encode, EncodeValue, Decode and DecodeValue.


  1. https://blog.golang.org/gobs-of-data
  2. https://golang.org/pkg/encoding/gob/
  3. http://www.robotamer.com/code/go/gotamer/gob.html
  4. https://github.com/alecthomas/go_serialization_benchmarks
  5. https://appliedgo.net/networking/

 Click here to Go to Part 2

  • Share:

Leave a comment