How to Pass a Map to a Function in Go

1. Introduction

In Go, maps are reference types that point to an underlying data structure. This means when you pass a map to a function, it does not create a copy of the map. Any changes the function makes to the map will be seen by the caller, making maps a convenient way to share and modify data across different parts of your program. This post will show how to pass a map to a function in Go and modify the original map within that function.

2. Program Steps

1. Declare and initialize a map.

2. Pass the map to a function that modifies it.

3. Print the map before and after the function call to demonstrate that changes are visible to the caller.

3. Code Program

Passing a map to a function in Go involves providing the map as an argument to the function call. The function can then access and modify the map directly without needing to return it, as the map argument is a reference to the original map.

Here is the complete Go program to demonstrate how to pass Map to a function:
package main

import "fmt"

// modifyMap modifies the provided map by adding a new key-value pair
func modifyMap(m map[string]int) {
	m["newKey"] = 42
}

func main() {
	// Step 1: Declare and initialize a map
	myMap := make(map[string]int)
	myMap["existingKey"] = 7

	fmt.Println("Before modifyMap:", myMap)

	// Step 2: Pass the map to the function
	modifyMap(myMap)

	// Step 3: Print the map after the function call
	fmt.Println("After modifyMap:", myMap)
}

Output:

Before modifyMap: map[existingKey:7]
After modifyMap: map[existingKey:7 newKey:42]

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package for input and output operations.

3. modifyMap - A function that takes a map as its argument and adds a new key-value pair to it. Since maps are reference types in Go, the function modifies the map in place.

4. myMap - A map that is declared and initialized with a single key-value pair.

5. The initial state of myMap is printed to the console.

6. modifyMap is called with myMap as its argument, which adds a new key-value pair to the map.

7. The state of myMap is printed again, showing the modification made by modifyMap.

8. The output shows the contents of myMap before and after it is passed to modifyMap, confirming that the function has successfully modified the original map.


Comments