gpt4 book ai didi

go - 将嵌套结构保存到 gob

转载 作者:IT王子 更新时间:2023-10-29 01:44:20 47 4
gpt4 key购买 nike

我正在尝试将结构保存到 gob,但文件缺少嵌套类型的值。我可以自己保存 Matrix 类型,但 Network 结构的 gob 数据不包括 Matrix 值。有没有办法将这个嵌套结构保存到 gob 中,还是必须拆分它?

type Matrix [][]float64
type Network struct {
wih Matrix
who Matrix
}

谢谢!

最佳答案

您必须导出要编码的结构字段:

type Network struct {
Wih Matrix
Who Matrix
}

引用自 encoding/gob 的包文档:

Structs, arrays and slices are also supported. Structs encode and decode only exported fields.

导出字段后它将起作用。看这个例子:

n := Network{
Wih: Matrix{{1.1, 2.2}, {3.3, 4.4}},
Who: Matrix{{5.5, 6.6}, {7.7, 8.8}},
}
fmt.Println(n)

buf := &bytes.Buffer{}
if err := gob.NewEncoder(buf).Encode(n); err != nil {
panic(err)
}

var n2 Network
if err := gob.NewDecoder(buf).Decode(&n2); err != nil {
panic(n2)
}
fmt.Println(n2)

输出(在 Go Playground 上尝试):

{[[1.1 2.2] [3.3 4.4]] [[5.5 6.6] [7.7 8.8]]}
{[[1.1 2.2] [3.3 4.4]] [[5.5 6.6] [7.7 8.8]]}

关于go - 将嵌套结构保存到 gob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50045735/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com