Andrew
Andrew

Reputation: 2173

Go - map value doesn't update

I have some sample code here (runnable here: http://play.golang.org/p/86_EBg5_95)

package main

import "fmt"

type X struct {
    Y   int
}

func main() {
    m := make(map[int]X)
    var x *X
    if _, ok := m[0]; !ok {
        z := X{}
        m[0] = z
        x = &z
    }

    x.Y = 10
    fmt.Println(m[0].Y)
    fmt.Println(x.Y)
}

Basically: what am I missing here? Shouldn't m[0].Y be 10 as well?

Upvotes: 0

Views: 2619

Answers (1)

fredrik
fredrik

Reputation: 13550

x point to z while m[0] is a copy of z (it's a map[int]X and not a map[int]*X), so updating x.Y wont update m[0]

I'm not sure what you want to do, but here m is a map containing pointers:

func main() {
    m := make(map[int]*X)
    var x *X
    if _, ok := m[0]; !ok {
        z := X{}
        m[0] = &z
        x = &z
    }

    x.Y = 10
    fmt.Println(m[0].Y)
    fmt.Println(x.Y)
}

Upvotes: 3

Related Questions