Golang: Serialize struct using gob - Part 2

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

In this article we will explore following functions of gob

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

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

Encode and Decode functions are helpful when you want to write network application.

Example 1: Simple encoding and decoding student structure

It’s is a simple example. In which we serialize and deserialize Student Struct. After encoding Student struct, It stores in byte buffer “b” now, we can use variable “b” to transfer over the network. To Decode byte buffer, we just need to create the object of the same structure and provide the address of a variable. In above example we have “studentEncode” variable which we have used for encoding and studentDecode variable is used for decoding.

Example 2: Encoding student structure and pass over TCP connection.

TCP Client: It dial open TCP connection and transfer student object using gob.Encoder method.

TCP Server: It listen on port 8080, Handle all client connection in go routine. Decode Student structure using gob.Decoder and print.

Questions:

  1. What if you have different fields for Client and Server?
  2. What if you have same fields but different sequence?
  3. What if you have different data type for the fields?

Answer:

  1. Find your self 🙂

Reference

  1. https://blog.golang.org/gobs-of-data
  2. https://golang.org/pkg/encoding/gob/
  • Share:

Leave a comment