无法分配给映射中的结构字段 [英] Cannot assign to struct field in a map

查看:56
本文介绍了无法分配给映射中的结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据结构:

type Snapshot struct {
  Key   string
  Users []Users
}

snapshots := make(map[string] Snapshot, 1)

// then did the initialization
snapshots["test"] = Snapshot {
  Key: "testVal",
  Users: make([]Users, 0),
}

Users 是另一个结构.

然后,当我尝试在Users切片中添加一些新的 Users 值时,

Then when I tried to append some new Users values in the Users slice like this:

snapshots["test"].Users = append(snapshots["test"].Users, user)

我一直收到此错误:

cannot assign to struct field snapshots["test"].Users in map

也在此处 https://github.com/golang/go/issues/3117尝试解决方法这样:

tmp := snapshots["test"].Users
tmp = append(tmp, user)
snapshots["test"].Users = tmp

但是没有运气,还是完全一样的错误.

But no luck, still exactly same error.

并且还尝试使用指针声明地图,因此: snapshots:= make(map [string] * Snapshot,1),仍然没有运气.

And also tried to declare the map with pointer, so: snapshots := make(map[string] *Snapshot, 1), still no luck.

推荐答案

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

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...

是的,这就是原因.

这篇关于无法分配给映射中的结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆