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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
