GO GO

Maps in Go: Keeping a Greengrocer's Stock Without Inventing Mangoes

Dima Noi 17, 2026

Introduction

Almost every program needs to look something up by name: a price by product code, a score by player, a quantity by item. In Go the tool for that is the map, and it is one of the first things beginners reach for. Maps are easy to use and have three behaviours that surprise nearly everyone: a map that was declared but not created crashes the program the moment you write to it, a key that is not there quietly reads as zero, and the order in which a loop visits the keys changes from one run to the next.

In this tutorial we will keep the stock of a market stall in a map and update it as the day's sales come in. We will hit each of those surprises in turn: a panic on the very first line, a stock list that suddenly contains an item the stall has never sold, and a report whose order shuffles every time it runs. Each time we will look at why Go behaves this way and what the idiomatic fix is.

I will assume you are working in the Go sandbox on Bytestark, with the terminal in /home/coder/learning, which holds a Go module named learning. You should be able to run a small Go program with go run, and know what a variable, a function and a for loop are.


Background

A map stores key–value pairs. map[string]int is the type "a map from string keys to int values": you give it a name like "apples" and get back a number like 40. Each key appears at most once. Writing a value under an existing key replaces the old value.

You read and write a map with square brackets. stock["apples"] = 40 stores 40 under the key "apples", and stock["apples"] reads it back. len(stock) is the number of keys, and delete(stock, "apples") removes one.

Every Go type has a zero value, the value a variable of that type has before you give it one: 0 for int, "" for string, false for bool. For a map type, the zero value is nil, which means "no map at all". A nil map behaves like an empty map when you read from it, but there is nowhere to store anything in it. To get a real, usable map you create one, either with make or by writing its contents directly.

A map is a reference type: a map variable does not hold the data itself, it refers to it. If you pass a map to a function, the function sees the same data, and changes it makes are visible to the caller.


Practical Scenario

A family runs a fruit stall at a weekly farmers' market. In the morning they write down how many units of each fruit they brought: 40 apples, 25 pears, 18 plums, 12 punnets of cherries and 30 bags of apricots. During the day every sale is entered into a small program, and at closing time the program prints what is left and which items to reorder for next week.

The stock list drives real decisions. If the program shows stock that does not exist, a customer is promised fruit the stall cannot deliver. If it accepts a sale for something the stall never had, the numbers no longer match the cash box. And if the closing report comes out in a different order every week, the family stops trusting it and goes back to paper.

The rule for reordering is simple: anything with fewer than 10 units left goes on next week's order.


The Problem

Here is the first attempt. It declares the stock map and fills in the first two items.

Create a folder and a file for the program:

mkdir stock
touch stock/main.go


Put this in stock/main.go:

package main

import "fmt"

func main() {
    var stock map[string]int
    stock["apples"] = 40
    stock["pears"] = 25
    fmt.Println(stock)
}


Go into the folder and run it:

cd stock
go run .


panic: assignment to entry in nil map

goroutine 1 [running]:
main.main()
    /home/coder/learning/stock/main.go:7 +0x2c
exit status 2


The program crashed on its first real line. A panic is how a Go program stops when something happens that it cannot continue from. Let's read the message.

  • panic: assignment to entry in nil map is the reason: we tried to store a value in a map that is nil.
  • goroutine 1 [running]: says which line of execution was running. A goroutine is Go's unit of concurrent work; a simple program has only one, number 1.
  • main.main() is the function that was running: function main in package main.
  • /home/coder/learning/stock/main.go:7 is the exact line, stock["apples"] = 40. The +0x2c after it is a position in the compiled machine code and can be ignored.
  • exit status 2 is added by go run: the program ended with exit code 2, which is what a panic produces.

The cause is the first line of main. var stock map[string]int declares a variable of map type without giving it a value, so it gets the zero value for maps, nil. The declaration only says what kind of thing stock will refer to; it does not create a map for it to refer to. Reading from a nil map would have worked and returned 0, but writing has nowhere to put the value, so Go panics rather than silently doing nothing.


Creating a Map, and the Order of Its Keys

There are two ways to create a real map. make(map[string]int) creates an empty map you can fill afterwards. A map literal creates one with its contents written out. For a stall that knows its morning stock, the literal says it best. Replace the whole of main.go with:

package main

import "fmt"

func main() {
    stock := map[string]int{
        "apples":   40,
        "pears":    25,
        "plums":    18,
        "cherries": 12,
        "apricots": 30,
    }

    fmt.Println(stock)
    fmt.Println("items:", len(stock))

    for item, qty := range stock {
        fmt.Println(item, qty)
    }
}


Build it once and run it a few times:

go build && ./stock


map[apples:40 apricots:30 cherries:12 pears:25 plums:18]
items: 5
apricots 30
apples 40
pears 25
plums 18
cherries 12


Run the same executable again:

./stock


map[apples:40 apricots:30 cherries:12 pears:25 plums:18]
items: 5
pears 25
plums 18
cherries 12
apricots 30
apples 40


The map works now. The literal map[string]int{ ... } creates the map and fills it in one step. Each line inside the braces is key: value, and the comma after the last line is required in Go whenever the closing brace is on its own line.

Look at the two runs, though. The first two lines are identical, and the five lines from the loop are in a different order. Your own runs will show yet other orders. Nothing in the program changed. This is deliberate in Go: a for ... range loop over a map visits the keys in an order that is not specified, and Go actually picks a different starting point each time on purpose. The language designers did this so that nobody writes code that accidentally depends on map order, which would break the day the internal layout of the map changes.

fmt.Println(stock) is the exception. When fmt prints a whole map, it sorts the keys first, precisely so that printed maps are readable and stable. That is why the first line is the same every time and in alphabetical order. The range loop gets no such help.

In the loop, for item, qty := range stock gives you each key in item and its value in qty. len(stock) is the number of keys, 5.

Try it: Replace the literal with stock := make(map[string]int) followed by stock["apples"] = 40 and stock["pears"] = 25 on two separate lines, and delete the len line and the loop so only fmt.Println(stock) remains. Before you run it, predict whether it panics like the first version. It does not: it prints map[apples:40 pears:25], because make creates a real, empty map, whereas var only declared a nil one. Put the literal version back.


Missing Keys Read as Zero

Now the sales. We put the stock update in a function, so every sale goes through one place. Replace the whole of main.go with this version, which defines sell and records four sales, the last one for mangoes:

package main

import "fmt"

func sell(stock map[string]int, item string, qty int) {
    stock[item] -= qty
}

func main() {
    stock := map[string]int{
        "apples":   40,
        "pears":    25,
        "plums":    18,
        "cherries": 12,
        "apricots": 30,
    }

    sell(stock, "apples", 12)
    sell(stock, "plums", 15)
    sell(stock, "cherries", 3)
    sell(stock, "mangoes", 2)

    fmt.Println(stock)
}


go run .


map[apples:28 apricots:30 cherries:9 mangoes:-2 pears:25 plums:3]


The three real sales worked: apples went from 40 to 28, plums from 18 to 3, cherries from 12 to 9. And the stall now has minus two mangoes, an item it has never stocked.

Two things happened here. First, notice that sell changed the map that lives in main, even though it received stock as an ordinary parameter. That is the reference behaviour from the Background: the function got a reference to the same map, not a copy, so its changes are visible in main. That part is exactly what we want.

Second, stock[item] -= qty is short for stock[item] = stock[item] - qty, and it does the mangoes damage in two steps. Reading stock["mangoes"] for a key that is not in the map does not fail: it returns the zero value for int, which is 0. Then the assignment stores 0 - 2 under "mangoes", which creates the key. A map read can never tell you, by its value alone, whether a key was missing or present with a zero value.

That ambiguity matters for a stock list, because "zero apricots left" and "we don't sell apricots" are different facts. Go's answer is the comma-ok form of a map read. Replace the sell function with:

func sell(stock map[string]int, item string, qty int) {
    have, ok := stock[item]
    if !ok {
        fmt.Println("unknown item:", item)
        return
    }
    if qty > have {
        fmt.Println("not enough", item+":", "only", have, "left")
        return
    }
    stock[item] = have - qty
}


And replace the sales in main with this list, which adds an attempt to oversell cherries and two apricot sales, the second one after the apricots have run out:

    sell(stock, "apples", 12)
    sell(stock, "plums", 15)
    sell(stock, "cherries", 3)
    sell(stock, "mangoes", 2)
    sell(stock, "cherries", 20)
    sell(stock, "apricots", 30)
    sell(stock, "apricots", 1)


go run .


unknown item: mangoes
not enough cherries: only 9 left
not enough apricots: only 0 left
map[apples:28 apricots:0 cherries:9 pears:25 plums:3]


No more mangoes. Let's go through the new sell.

  • have, ok := stock[item] reads the map with two variables on the left. have gets the value, exactly as before. ok is a bool that is true if the key was in the map and false if it was not. This is the only way to tell a missing key from a key whose value happens to be 0.
  • if !ok (read "if not ok") handles the missing key: it reports the unknown item and returns from the function without touching the map. mangoes is never created.
  • if qty > have refuses to sell more than there is. Without it, overselling cherries would have produced a negative stock just like the mangoes did.
  • stock[item] = have - qty writes the new quantity only after both checks have passed.

The output shows each check doing its job. Mangoes are unknown. The second cherry sale asks for 20 when 9 are left. The first apricot sale empties the bags, 30 of 30, and the second finds 0 left, which is an existing item with a zero value, not a missing one, so it is reported as "not enough", not "unknown". The map at the end lists only real items.

Try it: Replace the first three lines of sell with have := stock[item] and if have == 0 {, so the function tests the value instead of ok. Predict the third line of output. It becomes unknown item: apricots: once apricots are sold out, their value is 0, and a test on the value alone cannot tell "sold out" from "never stocked". Put the comma-ok version back.


A Report in a Stable Order

fmt.Println(stock) is fine for debugging, but the closing report should list each item on its own line, flag the ones to reorder, and come out in the same order every week. A range loop over the map cannot promise that. The standard approach is to collect the keys into a slice, sort the slice, and then loop over the sorted keys.

First, change the import line to import two packages:

import (
    "fmt"
    "sort"
)


Then replace the final fmt.Println(stock) in main with:

    items := make([]string, 0, len(stock))
    for item := range stock {
        items = append(items, item)
    }
    sort.Strings(items)

    fmt.Println("End of day:")
    for _, item := range items {
        qty := stock[item]
        if qty < 10 {
            fmt.Printf("  %-9s %3d  REORDER\n", item, qty)
        } else {
            fmt.Printf("  %-9s %3d\n", item, qty)
        }
    }


go run .


unknown item: mangoes
not enough cherries: only 9 left
not enough apricots: only 0 left
End of day:
  apples     28
  apricots    0  REORDER
  cherries    9  REORDER
  pears      25
  plums       3  REORDER


The report is in alphabetical order, and it will be in exactly this order on every run, because the loop now goes over a sorted slice, not over the map. Three items are under 10 and marked for reordering. Here is how the new block works.

  • items := make([]string, 0, len(stock)) creates an empty slice of strings. The 0 is its starting length. The len(stock) is its capacity, the room set aside in advance, so that appending five names never has to grow the slice. Leaving the capacity out would work too; it only saves Go some copying.
  • for item := range stock with a single variable visits just the keys. The order is still random here, and that does not matter, because...
  • items = append(items, item) adds each key to the end of the slice. append returns the updated slice, which is why its result is assigned back to items.
  • sort.Strings(items) sorts the slice in place, alphabetically. This one line is what makes the report stable.
  • for _, item := range items loops over the sorted slice. range over a slice gives the position and the element; we do not need the position, so we put the blank identifier _ in its place. Go does not let you declare a variable and not use it, so _ is how you say "I am ignoring this".
  • qty := stock[item] reads each quantity. A plain read is safe here, because every name in items came from the map itself, so the key is always present.
  • %-9s prints the name left-aligned in 9 characters, and %3d prints the number right-aligned in 3, which lines up the columns.

Try it: Delete the line sort.Strings(items) and run go run .. Predict what happens. You may expect a shuffled report, but the program does not compile: "sort" imported and not used. Go's rule about unused imports caught that the only use of the package was gone. If you also remove "sort" from the import, the report runs, and its order changes between runs, exactly like the range loop in the first section. Put both back.


Removing Items With delete

Apricot season is over. The bags sold out today and will not come back until next summer, so apricots should leave the stock list instead of sitting at zero and asking to be reordered. Mangoes, meanwhile, were never in the map at all. Add these lines in main, just before the line that creates items:

    fmt.Println("items before:", len(stock))
    delete(stock, "apricots")
    delete(stock, "mangoes")
    fmt.Println("items after:", len(stock))


go run .


unknown item: mangoes
not enough cherries: only 9 left
not enough apricots: only 0 left
items before: 5
items after: 4
End of day:
  apples     28
  cherries    9  REORDER
  pears      25
  plums       3  REORDER


Apricots are gone from the report, and the map went from 5 keys to 4. delete(stock, "apricots") removes the key and its value. A later stock["apricots"] would read 0 again, but with ok set to false, and the comma-ok check in sell would now call apricots an unknown item, which is exactly right for a fruit out of season.

delete(stock, "mangoes") removed nothing, and that is not an error: deleting a key that is not there does nothing. That is why the count dropped by one, not two. Go chose this so that code that wants "make sure this key is gone" does not need a check first.

The position of these lines matters. They run before the keys are collected into items, so the slice never contains apricots. If you deleted after building the slice, the report would still list apricots: the name would still be in items, and stock["apricots"] would quietly read as 0 for a key that no longer exists.

Try it: Change delete(stock, "apricots") to delete(stock, "Apricots") with a capital A. Predict the two items lines and whether apricots appear in the report. You get items before: 5 and items after: 5, and apricots are back with 0 REORDER. Map keys are compared exactly, "Apricots" is a different string from "apricots", and deleting a key that is not there is silently allowed. Put the lowercase name back.


Summary

We built the stock list of a market stall on a Go map, updated it from the day's sales without inventing items that were never sold, printed a closing report in a stable order, and removed a fruit at the end of its season. We kept the sales in the code to focus on maps. Reading them from a file, and storing a price next to each quantity with a struct, are natural next steps.

  • A map declared with var m map[K]V is nil: reading from it returns zero values, but writing to it panics with assignment to entry in nil map. Create maps with make(map[K]V) or a map literal.
  • A map is a reference type, so a function that receives a map can change the caller's data.
  • Reading a missing key returns the zero value of the value type, and m[k] -= n on a missing key creates it. Use v, ok := m[k] whenever "missing" and "zero" mean different things.
  • range over a map visits keys in a deliberately unspecified order that changes between runs. For stable output, collect the keys into a slice, sort it with sort.Strings, and loop over the slice.
  • fmt.Println sorts map keys when it prints a whole map, which is why printed maps look stable even though range is not.
  • Use the blank identifier _ for values you must receive but do not use, such as the index in for _, x := range items.
  • delete(m, k) removes a key, and deleting a key that is not present is allowed and does nothing.
  • Map keys are compared exactly, so a difference in capitalisation is a different key.

Trebuie să fii autentificat pentru a accesa laboratorul cloud.

Autentifică-te