Here's my code:
func test(v map[string]string) {
v["foo"] = "bar"
}
func main() {
v := make(map[string]string)
test(v)
fmt.Printf("%v
", v) // prints map[foo:bar]
}
I'm pretty new to Go, but as far as I was aware, since I'm passing the map value to test()
and not a pointer to the map, the test()
function should modify a different variable of the map, and thus, not affect the value of the variable in main()
. I would have expected it to print map[]
. I tested a different scenario:
type myStruct struct {
foo int
}
func test2(v myStruct) {
v.foo = 5
}
func main() {
v := myStruct{1}
test2(v)
fmt.Printf("%v
", v) // prints {1}
}
In this scenario, the code behaves as I would expect. The v
variable in the main()
function is not affected by the changes to the variable in test2()
. So why is map different?