search

How to initialize a map literal in Go?

In Go, a map is a built-in data structure that associates a set of keys with a set of values. You can use map literals to initialize maps with a set of key-value pairs.

A map literal is a shorthand notation for initializing a map with a set of key-value pairs. The syntax for a map literal is as follows:

mapName := map[keyType]valueType{
    key1: value1,
    key2: value2,
    ...
}

Here, **mapName** is the name of the map, **keyType** is the type of the keys, and **valueType** is the type of the values. The curly braces **{}** enclose the key-value pairs.

For example, let's say you want to create a map that associates the names of some programming languages with their corresponding popularity rankings:

languages := map[string]int{
    "Java":   1,
    "Python": 2,
    "C++":    3,
    "JavaScript": 4,
}

In this example, the keys are strings representing the names of programming languages, and the values are integers representing their popularity rankings.

You can also create an empty map and add key-value pairs to it using the map literal syntax:

m := map[string]int{}
m["foo"] = 42
m["bar"] = 12

Here, we first create an empty map **m** with a key type of **string** and a value type of **int**, and then add two key-value pairs to it using the map indexing syntax.

Using map literals to initialize maps is a concise and convenient way to create maps with predefined key-value pairs.

Related Questions You Might Be Interested