Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 769
siritinga Avatar asked Oct 19 '25 04:10

siritinga


1 Answers

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]
like image 59
peterSO Avatar answered Oct 20 '25 19:10

peterSO