In Go, maps are built-in data structures that store unordered collections of key-value pairs. They provide fast lookups, updates, and deletions based on keys.
You can declare a map using the map[keyType]valueType
syntax. Maps must be initialized before use, typically with make()
or a map literal.
var colors map[string]string // Declared, but nil and unusable yet colors = make(map[string]string) // Initialized and ready to use // Or declare and initialize with values using a map literal fruits := map[string]string{ "a": "Apple", "b": "Banana", "c": "Cherry", }
Add or update map entries by assigning a value to a key:
colors := make(map[string]string) colors["red"] = "#FF0000" // Add a key-value pair colors["green"] = "#00FF00" // Add another colors["red"] = "#F00" // Update the value for "red"
Retrieve values by key. If the key doesnβt exist, the zero value for the value type is returned:
colorCode := colors["red"] fmt.Println(colorCode) // Output: #F00 unknown := colors["blue"] fmt.Println(unknown) // Output: "" (empty string)
Use the two-value assignment to check if a key exists:
value, exists := colors["blue"] if exists { fmt.Println("Blue color code:", value) } else { fmt.Println("Blue key not found") }
Use the built-in delete()
function to remove a key-value pair:
delete(colors, "green") // Removes the "green" key
Use a for range
loop to iterate through all key-value pairs:
for key, value := range colors { fmt.Printf("Key: %s, Value: %s\n", key, value) }
Maps in Go offer a flexible and efficient way to manage key-value data. With built-in support for creation, access, update, deletion, and iteration, they are a fundamental data structure youβll use frequently.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!