修改一个作为映射值的数组。

huangapple go评论90阅读模式
英文:

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

你的map值(arrays)是不可寻址的,根据规范

> 每个左操作数必须是可寻址的

如果你真的想使用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"])

huangapple
  • 本文由 发表于 2013年12月30日 01:04:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/20827771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定