为什么 map value 是 struct 的时候 无法改变 struct 的变量呢? 迷惑啊

2018-03-12 22:01:55 +08:00
 admirez
type data struct {
name string
}

func main() {
m := map[string]data {"x":{"one"}}
m["x"].name = "two" //cannot assign to struct field m["x"].name in map
}
1063 次点击
所在节点    Go 编程语言
6 条回复
btjoker
2018-03-12 22:07:03 +08:00
因为你取到的是复制品啊
m := map[string]data {
"x": data {"one"}
}
n := data {"two"}
m[x] = n
btjoker
2018-03-12 22:10:01 +08:00
不好意思, 引号和逗号掉了
雨痕的 Go 学习笔记, 建议看看
fuxiaohei
2018-03-12 22:12:45 +08:00
https://golang.org/ref/spec#Assignments

Each left-hand side operand must be addressable, a map index expression, or (for = assignments only) the blank identifier. Operands may be parenthesized.

https://golang.org/ref/spec#Address_operators

For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal. If the evaluation of x would cause a run-time panic, then the evaluation of &x does too.

赋值的对象必须是 addressable,用 *T 吧
laike9m
2018-03-12 22:21:11 +08:00
admirez
2018-03-12 22:41:39 +08:00
嗯,用*T 搞定了
ox180
2018-03-13 12:53:22 +08:00
```
func main(){
type data struct {
name string
}


s := make(map[int]*data)

s[1] = &data{name: "aa"}

s[1].name = "bb"

fmt.Println(*s[1])

}
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/437428

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX