Search code examples
dictionarygointerface

How does value change in Golang Map of interface


This is the code base - https://go.dev/play/p/BeDOUZ9QhaG

Output -

map[something:map[ACM:34.12 age:12 dune:dune]]

How does changing values in t variable affect in x?

package main

import "fmt"

    func main() {
        x: = make(map[string] interface {}, 10)
        x["something"] = map[string] interface {} {
            "dune": "dune", "age": 12
        }
    
        t: = x["something"].(map[string] interface {})
        t["ACM"] = 34.12
       

 fmt.Println(x)
}

Solution

  • Map types are reference types, like pointers or slices,

    so this line

    t := x["something"].(map[string]interface{}) t["ACM"] = 34.12 fmt.Println(x) }
    

    is just a shallow copy creating alias for the existing map you created above in x variable ,so they are pointing to same memory address where the original map you created exists.

    See for reference -https://go.dev/blog/maps