Problem: You want to encode structs into binary gob format.
Solution: Use the encoding/gob package to encode the structs into bytes that can be stored or sent elsewhere.
The encoding/gob package is a Go library to encode and decode a binary format. The data can be anything but is particularly useful with Go structs. You should be aware that gob is a proprietary Go binary format. Although there are attempts to decode gob in other languages, it is not a widely used format like protobuf or Thrift. It is advisable to use a more commonly used format if you have more complex use cases for binary data.
Take a look at an example. You want to deploy small electricity meters all over a building to measure the consumption of energy in the building. The metering points are not only per floor but also per unit, per area, and even per meeting room. They will also be used in common areas, including lighting as well as larger loads like lifts and escalators. The information you gather will help you monitor any abnormal usage of electricity, identify wastage, and allocate costs to the different occupants of the building. You are going to deploy a lot of these meters all over the building so the communications use a low-powered wide area network (LP-WAN). Your requirement is for data packets to be small so they can be transported through the LP-WAN efficiently.
Start with a simple struct to capture the information from the meter:
type Meter struct { Id uint32 Voltage float32 Current float32 Energy uint32 Timestamp uint64 }
You set a unique identifier for each meter; the voltage, current, and energy are what is being measured; and the timestamp gives you the time the reading is taken. The voltage and current are measured at the moment, but the energy in kilowatt-hours is how much energy has been consumed since the meter started.
Next, see how you can take readings from the meter and write them to a stream to be sent across the LP-WAN. For this, you will assume the following meter-reading data will be available and construct a struct to contain the data:
var reading Meter = Meter{ Id: 123456, Voltage: 229.5, Current: 1.3, Energy: 4321, Timestamp: uint64(time.Now().UnixNano()), }
You also use a file to represent the network and will write to it:
func write(data interface{}, filename string) { file, err := os.Create(filename) if err != nil { log.Println("Cannot create file:", err) } defer file.Close() encoder := gob.NewEncoder(file) err = encoder.Encode(data) if err != nil { log.Println("Cannot encode data to file:", err) } }
First, you create a file , which will be your Writer. You then create an encoder around this writer and call Encode on it, passing it the struct instance. This will encode the struct instance in the gob format and will write it to a file.