Passing Go Map as Function Argument

A map is a built-in type that associates a set of keys with corresponding values. It is a collection of key-value pairs that allows efficient lookup, insertion, and deletion operations. Maps in Go are similar to dictionaries in other programming languages.

To pass a map as a function argument in Go, you can simply declare the function with a parameter of the map type. Here’s an example:

func processMap(m map[string]int) {
    for key, value := range m {
        fmt.Printf("Key: %s, Value: %d\n", key, value)

In this example, the processMap function takes a map with string keys and integer values as its argument. It then iterates over the key-value pairs using a for loop and prints them to the console.

You can call this function and pass a map to it like this:

myMap := map[string]int{"apple": 1, "banana": 2, "orange": 3}

This code creates a map with three key-value pairs and passes it to the processMap function. The output of this code will be:

Key: apple, Value: 1
Key: banana, Value: 2
Key: orange, Value: 3
Follow us on social media
Follow Author