Go Map
In Go, a map is a built-in data structure that allows you to store and retrieve key-value pairs. The keys and values can be of any type, as long as they are comparable. Maps are implemented as hash tables, which provide fast lookup times for keys.
The syntax for creating a map in Go is as follows:
var mapName map[keyType]valueType
Here's an example of creating a map that maps strings to integers:
var scores map[string]int
In this example, a map named scores
is created with keys of type string
and values of type int
. The map is initialized to a zero value of nil
, which means it doesn't yet point to an underlying hash table.
You can also initialize a map with key-value pairs when it is created, like this:
scores := map[string]int{ "Alice": 90, "Bob": 85, "Charlie": 80, }
In this example, the scores
map is created and initialized with three key-value pairs.
You can add key-value pairs to a map using the following syntax:
scores["Dave"] = 95
In this example, a new key-value pair is added to the scores
map that maps the string "Dave" to the integer value 95.
You can retrieve the value associated with a key in a map using the following syntax:
fmt.Println(scores["Bob"])
In this example, the value associated with the key "Bob" in the scores
map is printed to the console.
You can delete a key-value pair from a map using the delete
function, like this:
delete(scores, "Charlie")
In this example, the key-value pair associated with the key "Charlie" is deleted from the scores
map.