siritinga
siritinga

Reputation: 4231

Modify an array that is the value of a map

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?

Upvotes: 4

Views: 822

Answers (3)

Tim Pierce
Tim Pierce

Reputation: 5664

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"])

Upvotes: 0

Salah Eddine Taouririt
Salah Eddine Taouririt

Reputation: 26415

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.

Upvotes: 0

peterSO
peterSO

Reputation: 166626

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]

Upvotes: 4

Related Questions