且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法分配给映射中的结构字段

更新时间:2023-01-16 09:23:42

首先,对于这个问题,本文中的解决方案的工作原理很好.

First, for this question, the solution in this post Why do I get a "cannot assign" error when setting value to a struct as a value in a map? works perfectly fine.

然后,最后弄清楚为什么在我已经更改为使用指针之后,我的情况仍然无法使用,请参考以下非常简单的代码:

Then, finally figured out why after I already changed to use pointer my case still doesn't work, refer to the below very simple code:

a := make([]int, 3)
fmt.Println(len(a))

b := make(map[string]string, 3)
fmt.Println(len(b))

输出结果如何?我只是以为全部是: 3 ,但是实际上对于地图而言,输出将是 0

What do think the output will be? I simply thought it is all would be: 3, but actually for the map, the output will be 0

然后在地图初始化过程中,我使用了for循环,并使用 len(snapshots)这个值,这意味着初始化过程将永远不会运行...

Then later in the map initialization process, i used a for loop and with this value len(snapshots), that means the initialization process will never get run...

是的,这就是原因.