Sobes.tech
Senior

Is a map passed by reference to a function in Go?

sobes.tech AI

Answer from AI

In Go, a map is passed to a function by value, but it is important to understand that the value is a pointer to the internal data structure of the map. This means that when passing a map to a function, only the pointer to it is copied, not the entire structure.

As a result, inside the function, you can modify the contents of the map (add, delete, change elements), and these changes will be visible outside. However, if you assign a new map to the map variable inside the function, it will not affect the original map.

Example:

func modifyMap(m map[string]int) {
    m["key"] = 42 // will modify the original map
    m = make(map[string]int) // assigning a new map does not affect the external map
    m["newKey"] = 100
}

func main() {
    myMap := map[string]int{"original": 1}
    modifyMap(myMap)
    fmt.Println(myMap) // Will output: map[original:1 key:42]
}
Is a map passed by reference to a function in Go… - sobes.tech