CodeBlanks Logo Icon CodeBlanks

Map declaration

Learn to declare a key-value map with make.

Defining maps

A map is a data structure that maps keys to values; lookup by key is very fast. Its type is written map[KeyType]ValueType:

fiyat := map[string]float64{
    "kalem":  12.5,
    "defter": 20,
}
stok := make(map[string]int)
fmt.Println(fiyat["kalem"], len(fiyat))  // 12.5 2

The key type must be comparable with == (string, numbers, structs...); slices and maps can't be keys.

A map is a reference

A map variable carries a reference to the underlying data structure. Passing a map to a function or assigning it to another variable doesn't copy it; changes are visible everywhere:

func ekle(m map[string]int) {
    m["yeni"] = 1
}

m := map[string]int{}
ekle(m)
fmt.Println(len(m))  // 1

Maps aren't safe for concurrent writes; if several goroutines will write, a lock is needed.

Practice Price table

Declare fiyat := map[string]float64{"kalem": 12.5, "defter": 20}. Add fiyat["silgi"] = 4 and print the number of keys and the eraser's price on one line.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    fiyat := map[string]float64{"kalem": 12.5, "defter": 20}
    fiyat["silgi"] = 4
    fmt.Println(len(fiyat), fiyat["silgi"])
}

Expected output

3 4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens when <code>var m map[string]int; m["a"] = 1</code> runs?

  • A panic: you can't write to a nil map Correct answer
  • m["a"] becomes 1
  • A compile error
  • Nothing happens

Explanation: A map declared with var is nil; it can be read but not written. Create it first with make or a literal.

2 Create a map

Question
stok := ____(map[string]int)
stok["kalem"] = 3
Answer
stok := make(map[string]int)
stok["kalem"] = 3

Explanation: make creates an empty, writable map.

3 Code and result

Term Meaning
map[string]int{"a": 1} Map from a literal
make(map[string]int) Empty map
var m map[string]int nil map
len(m) Number of keys

All lessons in Beginner