Go Maps
Go - Maps
Section titled “Go - Maps”Go provides a powerful built-in data type called map, which stores collections of key-value pairs. Maps are also known as hash maps or dictionaries in other languages. Keys in a map must be unique and of a comparable type (e.g., strings, integers, booleans, pointers, structs with comparable fields). Values can be of any type.
Defining and Initializing a Map
Section titled “Defining and Initializing a Map”Maps must be initialized before they can be used. The make function is the standard way to create an initialized map. An uninitialized map is nil and attempting to add elements to a nil map will cause a runtime panic.
// Declare a map variable (it will be nil by default)var countryCapitalMap map[string]string
// Initialize the map using makecountryCapitalMap = make(map[string]string)
// Alternatively, declare and initialize in one step// capitals := make(map[string]string)
// You can also initialize a map with values using a map literal:capitals := map[string]string{ "France": "Paris", "Japan": "Tokyo",}Example: Working with Maps
Section titled “Example: Working with Maps”This example demonstrates creating a map, adding key-value pairs, accessing values, checking for key existence, and iterating over a map.
package main
import "fmt"
func main() { // Create and initialize a map using make countryCapitalMap := make(map[string]string)
// Insert key-value pairs into the map countryCapitalMap["France"] = "Paris" countryCapitalMap["Italy"] = "Rome" countryCapitalMap["Japan"] = "Tokyo" countryCapitalMap["India"] = "New Delhi"
// Print map using keys (iteration order is not guaranteed) fmt.Println("Iterating through the map:") for country, capital := range countryCapitalMap { fmt.Printf("Capital of %s is %s\n", country, capital) }
// Accessing a value fmt.Println("\nCapital of Japan is:", countryCapitalMap["Japan"])
// Checking if a key exists (the "comma ok" idiom) // If a key doesn't exist, accessing it directly returns the zero value for the value type. // To distinguish between a stored zero value and a non-existent key, use the two-value assignment. capital, ok := countryCapitalMap["United States"] if ok { fmt.Println("Capital of United States is", capital) } else { fmt.Println("Capital of United States is not present in the map.") }
// Accessing a non-existent key without the "comma ok" idiom returns the zero value // For string values, the zero value is an empty string. fmt.Println("Capital of Germany (not present): '", countryCapitalMap["Germany"], "'")}When the above code is compiled and executed, it produces a result similar to the following (note: map iteration order is random):
Iterating through the map:Capital of India is New DelhiCapital of France is ParisCapital of Italy is RomeCapital of Japan is Tokyo
Capital of Japan is: TokyoCapital of United States is not present in the map.Capital of Germany (not present): ''The delete() function
Section titled “The delete() function”The built-in delete() function removes an entry from a map. It takes the map and the key to be deleted as arguments. If the key is not present in the map, delete() is a no-op (it does nothing and does not panic).
package main
import "fmt"
func main() { // Initialize a map using a map literal countryCapitalMap := map[string]string{ "France": "Paris", "Italy": "Rome", "Japan": "Tokyo", "India": "New Delhi", }
fmt.Println("Original map:") for country, capital := range countryCapitalMap { fmt.Printf("Capital of %s is %s\n", country, capital) }
// Delete an entry delete(countryCapitalMap, "France") fmt.Println("\nEntry for France is deleted.")
// Delete a non-existent entry (no error) delete(countryCapitalMap, "Germany") fmt.Println("Attempted to delete entry for Germany (no error if not present).")
fmt.Println("\nUpdated map:") for country, capital := range countryCapitalMap { fmt.Printf("Capital of %s is %s\n", country, capital) }}When the above code is compiled and executed, it produces a result similar to this (iteration order may vary):
Original map:Capital of France is ParisCapital of Italy is RomeCapital of Japan is TokyoCapital of India is New Delhi
Entry for France is deleted.Attempted to delete entry for Germany (no error if not present).
Updated map:Capital of Italy is RomeCapital of Japan is TokyoCapital of India is New DelhiAdditional Notes on Maps:
- Comparable Keys: Map keys must be of a type that supports comparison (e.g.,
==and!=). Slices, maps, and functions cannot be map keys. - Concurrency: Maps are not safe for concurrent read/write access. If multiple goroutines access a map, you must synchronize access using mutexes (e.g.,
sync.RWMutex) or usesync.Mapfor specific concurrent use cases. - Zero Value: The zero value of a map type is
nil. Anilmap has no keys, nor can keys be added.