Map Declaration and Initialization
We can declare an empty map using the make()
function. Below is the syntax we need to follow:
python9123var mapName = make(map[keyType]valueType)// ormapName := make(map[keyType]valueType)
Here, mapName
is the name of the map, keyType
is the expected type of the keys, and valueType
is the expected type of the values. The term map
is a keyword.
We can declare a map called courseData
with keys of type string
and values of type int
.
index
1var courseData = make(map[string]int)
If we attempt to output this map, we will receive an output indicating an empty map:
index
1fmt.Println(courseData) // Output: map[]
We can initialize a map with some data using the following syntax:
python9123456var mapName = map[keyType]valueType = {key1: value1,key2: value2,key3: value 3,…}
Note
You can place or omit spaces in the map declaration syntax; therefore, both
map[keyType]valueType
andmap [keyType] valueType
are valid.
Using the above syntax, we can create a map that has some initial data in it:
index
1234567myMap := map[string]int { "a": 10, "b": 11, "c": 12, } fmt.Println(myMap) // Output: map[a:10 b:11 c:12]
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla