Go from zero: make the map before you write
A map has to be made before a write. map[string]int{} makes a menu. The program stores 450 under latte and prints 450.
Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.
A map is a set of keys and values. A menu is a map from the drink's name to its price in cents. The zero value of a map is nil. Reading a missing key from a nil map returns the zero of the value type. Writing to a nil map panics. The tip is short: make the menu before anyone writes a price into it.
A nil map can be read and must not be written#
The zero of a map is nil, and nil is not an empty menu. A read of a missing key returns the zero of the value type, so a nil map answers 0 cents for a drink and does not panic. A write needs a header that points at buckets. A nil map has no header, so the write stops the program. map[string]int{} allocates that header and stores no pairs. After that, a missing drink is still 0, which is why a two-result read exists when 0 is also a legal stored price.
- menu["latte"] = 450nil mappanic
package main
import "fmt"
func main() {
menu := map[string]int{}
menu["latte"] = 450
fmt.Println(menu["latte"])
}
450
The braces make the menu#
map[string]int{} is a map from string keys to int values, and the {} makes it. It starts empty, which is different from nil. menu["latte"] = 450 is a write. menu["latte"] is a read, and it prints 450, the cents you would charge.
var menu map[string]int with no {} is nil. The line menu["latte"] = 450 then stops the program with a panic: assignment to entry in nil map. The panic names the line of the write. The fix is the {} you see here, or make(map[string]int). Both give you a menu that can take a price.
A missing drink is still a zero#
After the map exists, menu["missing"] is 0. That 0 is the zero of int, the same zero as the previous lesson. It does not tell you whether the drink was stored at 0 cents or never stored. When that difference matters, use the two-result read: cents, ok := menu["latte"]. ok is true when the drink is on the menu. The next lesson puts a price in a struct and changes it through a method.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.