英文:
Modify an array that is the value of a map
问题
如果我有一个值为数组的地图,我该如何修改数组的一个元素?
类似这样:
m := make(map[string][4]int)
m["a"] = [...]int{0, 1, 2, 3}
m["a"][2] = 10
这段代码无法编译通过:prog.go:8: cannot assign to m["a"][2]
我可以将变量复制到一个数组中,修改它,然后再将其复制回地图,但这似乎非常慢,特别是对于大数组来说。
// 我想避免的方法。
m := make(map[string][4]int)
m["a"] = [...]int{0, 1, 2, 3}
b := m["a"]
b[2] = 10
m["a"] = b
有什么想法吗?
英文:
If I have a map whose value is an array, how can I modify one element of the array?
Something like this:
m := make(map[string][4]int)
m["a"]=[...]int{0,1,2,3}
m["a"][2]=10
It won't compile: prog.go:8: cannot assign to m["a"][2]
I could copy the variable to an array, modify it and then copying it back to the map, but it seems to be very slow, specially for large arrays.
// what I like to avoid.
m := make(map[string][4]int)
m["a"] = [...]int{0, 1, 2, 3}
b := m["a"]
b[2] = 10
m["a"] = b
Any idea?
答案1
得分: 4
使用指针。例如,
package main
import "fmt"
func main() {
m := make(map[string]*[4]int)
m["a"] = &[...]int{0, 1, 2, 3}
fmt.Println(*m["a"])
m["a"][2] = 10
fmt.Println(*m["a"])
}
输出:
[0 1 2 3]
[0 1 10 3]
英文:
Use a pointer. For example,
package main
import "fmt"
func main() {
m := make(map[string]*[4]int)
m["a"] = &[...]int{0, 1, 2, 3}
fmt.Println(*m["a"])
m["a"][2] = 10
fmt.Println(*m["a"])
}
Output:
[0 1 2 3]
[0 1 10 3]
答案2
得分: 0
> 每个左操作数必须是可寻址的
如果你真的想使用Arrays
,可以尝试@peterSO建议的方法,但我认为在这里使用Slices
更加习惯。
英文:
Your map value (arrays) is not addressable, From the spec:
> Each left-hand side operand must be addressable
Go for what @peterSO suggest if you really want to use Arrays
, but I think that Slices
here are more mush idiomatic.
答案3
得分: 0
如果你将字符串映射到切片而不是数组,这样就可以实现:
m := make(map[string][]int)
m["a"] = []int{0, 1, 2, 3}
fmt.Println(m["a"])
m["a"][2] = 10
fmt.Println(m["a"])
英文:
If you map strings to slices, rather than to arrays, this works:
m := make(map[string][]int)
m["a"] = []int{0, 1, 2, 3}
fmt.Println(m["a"])
m["a"][2] = 10
fmt.Println(m["a"])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论