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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律