Golang map as function parameter
package main
import (
"fmt"
)
func modifyMap(m map[string]int) {
m["one"] = 1
m["two"] = 2
}
func main() {
myMap := make(map[string]int)
myMap["zero"] = 0
fmt.Println("Before modification:", myMap)
modifyMap(myMap)
fmt.Println("After modification:", myMap)
}
Explanation of each step:
Import the necessary packages (
fmt
in this case) to use their functionalities.Define a function
modifyMap
that takes a mapm
as a parameter. Inside this function:Add key-value pairs to the map
m
: "one" with a value of 1 and "two" with a value of 2.Define the
main
function where the program execution begins:Create a map
myMap
usingmake
, initially setting a key "zero" with a value of 0.Print the contents of
myMap
before modification usingfmt.Println
.Call the
modifyMap
function, passing themyMap
as an argument. This will modify the contents ofmyMap
within the function.Print the contents of
myMap
after modification usingfmt.Println
. This demonstrates that changes made to the map inside themodifyMap
function reflect in the originalmyMap
as well.