Golang / GoLang Basics Interview Questions
How do maps work in Go? What are the key operations and pitfalls?
Maps are Go's built-in hash table. Keys must be comparable types (those that support == and !=). Maps are reference types — like slices, they are cheap to pass because only a header is copied.
// Creating maps m := map[string]int{} // empty map literal (ready to use) m2 := make(map[string]int) // same â make preferred when initial size is known m3 := map[string]int{ // initialised map "alice": 30, "bob": 25, } // Insert / update m3["carol"] = 28 m3["alice"] = 31 // update â no error if key exists // Read â returns zero value for missing keys, NOT an error age := m3["alice"] // 31 missing := m3["dave"] // 0 â zero value for int // Comma-ok idiom â check if key actually exists age, ok := m3["alice"] if ok { fmt.Printf("alice is %d\n", age) } // Delete delete(m3, "bob") // Iteration â ORDER IS NOT GUARANTEED for name, age := range m3 { fmt.Printf("%s: %d\n", name, age) } // PITFALL: reading nil map is OK (returns zero value) var bad map[string]int _ = bad["key"] // safe â returns 0 // bad["key"] = 1 // PANIC: assignment to entry in nil map
More Related questions...