Introduction
Maps help you store and find data quickly using keys, like a real-life dictionary.
var m map[keyType]valueType m = make(map[keyType]valueType) m[key] = value value = m[key] delete(m, key)
m := make(map[string]int) m["apple"] = 5 fmt.Println(m["apple"])
m := map[int]string{1: "one", 2: "two"} fmt.Println(m[2])
m := make(map[string]int) value, ok := m["banana"] if ok { fmt.Println("Found", value) } else { fmt.Println("Not found") }
package main import "fmt" func main() { // Create a map to count fruits fruitCount := make(map[string]int) // Add some fruits fruitCount["apple"] = 3 fruitCount["banana"] = 2 fruitCount["orange"] = 5 // Print counts fmt.Println("Apple count:", fruitCount["apple"]) fmt.Println("Banana count:", fruitCount["banana"]) // Check if "grape" exists if count, ok := fruitCount["grape"]; ok { fmt.Println("Grape count:", count) } else { fmt.Println("Grape not found") } // Remove "banana" delete(fruitCount, "banana") // Print map after deletion fmt.Println("After deleting banana:", fruitCount) }
map in Go?make(map[keyType]valueType). var m map[string]int = make(map[string]int) uses this correctly.m := make(map[string]int) m["apple"] = 5 m["banana"] = 3 fmt.Println(m["apple"] + m["banana"])
m stores integers with string keys. "apple" maps to 5, "banana" maps to 3.var m map[string]int m["key"] = 10 fmt.Println(m["key"])
m is declared but not initialized with make(). This causes a runtime panic on assignment.m["key"] = 10 causes a panic: assignment to nil map.m := map[string]int{"a": 1, "b": 0, "c": 3}, which code snippet correctly checks if key "b" exists and its value is non-zero?val, ok := m["b"] lets us check if key "b" exists (ok) and get its value (val).ok && val != 0 ensures key exists and value is not zero.Pass the test and this pattern moves unknown