ZhangZhihui's Blog  

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.

 

posted on   ZhangZhihuiAAA  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示