Problem: You want to decode gob format data back to structs.
Solution: Use the encoding/gob package to decode the gob format data back to structs.
func read(data interface{}, filename string) { file, err := os.Open(filename) if err != nil { log.Println("Cannot read file:", err) } defer file.Close() decoder := gob.NewDecoder(file) err = decoder.Decode(data) if err != nil { log.Println("Cannot decode data:", err) } }
Open the file. This file will be your Reader . You will create a decoder around the reader and then call Decode on it.
Call the read function and pass in a reference to a struct instance:
func main() { var reading Meter read(&reading, "reading") fmt.Printf("%#v\n", reading) fmt.Println("-----------------------------------------------------------------------------------------------") fmt.Printf("%# v\n", reading) fmt.Println("-----------------------------------------------------------------------------------------------") fmt.Printf("%+v\n", reading) }
The reading struct instance will be populated with the data after the call.
zzh@ZZHPC:/zdata/MyPrograms/Go/study$ go run main.go main.Meter{Id:0x1e240, Voltage:229.5, Current:1.3, Energy:0x10e1, Timestamp:0x1790e6a37141524a} ----------------------------------------------------------------------------------------------- main.Meter{Id: 0x1e240, Voltage: 229.5, Current: 1.3, Energy: 0x10e1, Timestamp: 0x1790e6a37141524a} ----------------------------------------------------------------------------------------------- {Id:123456 Voltage:229.5 Current:1.3 Energy:4321 Timestamp:1698110649172841034}
Encoding gob, as you can see, is faster than encoding JSON, though the amount of memory used is the same.
Decoding gob is much faster than decoding JSON as well and uses a lot less memory.