Exploring Maps
Deslize para mostrar o menu
Creating Maps in Go
A map in Go is a built-in data structure that stores key-value pairs. You use maps to associate values with unique keys, making it efficient to look up, add, or remove data by key.
Declaring an Empty Map
To create an empty map, use the make function with the desired key and value types:
myMap := make(map[string]int)
- This creates a map where the keys are of type
stringand the values are of typeint; - At this point,
myMapis empty and ready to store key-value pairs.
Initializing a Map with Values
You can also declare and initialize a map with values in a single statement using a map literal:
scores := map[string]int{
"Alice": 90,
"Bob": 85,
"Carol": 92,
}
- This creates a map named
scoreswith three key-value pairs; - The keys are student names, and the values are their corresponding scores.
Use these techniques to quickly set up maps for efficient data lookup and management in your Go programs.
main.go
123456789101112131415161718192021222324package main import ( "fmt" ) func main() { // Create a map to store country codes and their names countryCodes := make(map[string]string) // Add key-value pairs countryCodes["US"] = "United States" countryCodes["CA"] = "Canada" countryCodes["MX"] = "Mexico" // Access and print a value fmt.Println("US stands for:", countryCodes["US"]) // Modify an entry countryCodes["CA"] = "Canada (Modified)" // Print the updated map fmt.Println("All country codes:", countryCodes) }
Accessing and Modifying Key-Value Pairs in Maps
You use square brackets ([]) to access or update values in a Go map. The key goes inside the brackets. If you assign a value to a key, you add or update that entry in the map.
Accessing a value:
age := ages["Alice"]
If the key exists, age receives its value. If the key is not present, Go returns the zero value for the map's value type (for example, 0 for int, "" for string).
Modifying a value:
ages["Bob"] = 35
This sets the value for the key "Bob" to 35. If "Bob" was not already in the map, this adds a new entry.
Checking for Key Existence
To check if a key exists in a map, use the "comma ok" idiom. This lets you distinguish between a missing key and a key with the zero value:
value, ok := ages["Carol"]
okistrueif"Carol"is in the map;okisfalseif the key is not present.
This approach prevents you from confusing a missing key with a key set to the zero value.
Example:
ages := map[string]int{"Alice": 30, "Bob": 25}
age, ok := ages["Carol"]
if ok {
fmt.Println("Carol's age is", age)
} else {
fmt.Println("Carol is not in the map")
}
- If
"Carol"is not a key inages, the program printsCarol is not in the map. - If you add
ages["Carol"] = 28, the check will succeed and printCarol's age is 28.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo