Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

GO
Go
0/12 completed
Beginner
Hello GoTypes and variablesControl flowFunctions
Intermediate
Arrays, slices and mapsStructs and methodsInterfacesError handling
Advanced
GenericsGoroutines and channels
Pro
Building an HTTP serverModules, testing and tooling
Tracks / Go / Intermediate

Arrays, slices and maps

Go has three built-in collection types. Arrays have a fixed length and are rarely used directly. Slices are flexible views over arrays: they're Go's lists, and you'll use them constantly. Maps are hash tables from keys to values. Understanding how slices share memory is the key insight of this lesson.

Arrays

An array's length is part of its type: [3]int and [4]int are different types.

go
package main

import "fmt"

func main() {
	var a [3]int                      // [0 0 0]
	b := [3]string{"x", "y", "z"}
	c := [...]int{10, 20, 30, 40}      // the compiler counts: [4]int
	a[1] = 7
	fmt.Println(a, b, c, len(c))

	d := c                            // arrays are values: this COPIES all 4 ints
	d[0] = 99
	fmt.Println(c[0], d[0])
}
Output
[0 7 0] [x y z] [10 20 30 40] 4
10 99

Because arrays are copied when assigned or passed to a function, and their size is fixed, Go code almost always uses slices instead.

Slices

A slice is a small descriptor with three parts: a pointer to an underlying array, a length (how many elements you can use) and a capacity (how many fit before a bigger array is needed).

go
package main

import "fmt"

func main() {
	nums := []int{3, 1, 4}            // a slice literal (no size in the brackets)
	nums = append(nums, 1, 5, 9)      // append returns the (possibly new) slice
	fmt.Println(nums, len(nums))

	fmt.Println(nums[1:4])            // elements 1, 2, 3 (end is exclusive)
	fmt.Println(nums[:2], nums[3:])   // from the start / to the end

	empty := make([]string, 0, 10)    // length 0, capacity 10
	fmt.Println(len(empty), cap(empty), empty == nil)

	var none []int                    // nil slice: length 0, and append works
	none = append(none, 42)
	fmt.Println(none)
}
Output
[3 1 4 1 5 9] 6
[1 4 1]
[3 1] [1 5 9]
0 10 false
[42]

Always write s = append(s, …): when the capacity runs out, append allocates a bigger array, copies the elements, and returns a slice pointing to the new one.

How append grows a slice

go
package main

import "fmt"

func main() {
	var s []int
	prevCap := -1
	for i := range 2000 {
		s = append(s, i)
		if cap(s) != prevCap {
			fmt.Printf("len %4d → cap %4d\n", len(s), cap(s))
			prevCap = cap(s)
		}
	}
}
Output
len    1 → cap    4
len    5 → cap    8
len    9 → cap   16
len   17 → cap   32
len   33 → cap   64
len   65 → cap  128
len  129 → cap  256
len  257 → cap  512
len  513 → cap  848
len  849 → cap 1280
len 1281 → cap 1792
len 1793 → cap 2560

The capacity doubles while the slice is small, then grows by about 25% at a time, so appending is fast on average. If you know the final size, make([]T, 0, n) avoids all the copying.

Slices share memory

Slicing doesn't copy: the new slice looks at the same array. Changing one changes the other:

go
package main

import (
	"fmt"
	"slices"
)

func main() {
	original := []int{1, 2, 3, 4, 5}
	part := original[1:3]
	part[0] = 99
	fmt.Println("original:", original, "part:", part)

	// append into spare capacity also writes into the shared array!
	part = append(part, 100)
	fmt.Println("original:", original)

	// to get an independent copy:
	independent := slices.Clone(original)
	independent[0] = -1
	fmt.Println("original:", original, "clone:", independent)
}
Output
original: [1 99 3 4 5] part: [99 3]
original: [1 99 3 100 5]
original: [1 99 3 100 5] clone: [-1 99 3 100 5]

The second line is a classic surprise: part had spare capacity (it could see up to the end of original), so append wrote 100 over original[3]. When you need a slice you'll keep modifying separately, clone it (slices.Clone, or copy(dst, src)).

Functions receive a copy of the slice descriptor, but it points at the same array, so a function can change the elements:

go
package main

import "fmt"

func double(nums []int) {
	for i := range nums {
		nums[i] *= 2
	}
}

func main() {
	scores := []int{10, 20, 30}
	double(scores)
	fmt.Println(scores)
}
Output
[20 40 60]

The slices package

The standard slices package (Go 1.21+) has the operations you'd expect from a list type:

go
package main

import (
	"fmt"
	"slices"
)

func main() {
	nums := []int{42, 7, 19, 3, 25, 7}
	slices.Sort(nums)
	fmt.Println(nums)
	fmt.Println(slices.Contains(nums, 19), slices.Index(nums, 25))
	i, found := slices.BinarySearch(nums, 19)
	fmt.Println("binary search:", i, found)
	fmt.Println(slices.Max(nums), slices.Min(nums))
	nums = slices.Compact(nums)                       // remove consecutive duplicates
	fmt.Println(nums)
	nums = slices.Insert(nums, 1, 100)
	nums = slices.Delete(nums, 0, 1)
	fmt.Println(nums, slices.Equal([]int{1, 2}, []int{1, 2}))
}
Output
[3 7 7 19 25 42]
true 4
binary search: 3 true
42 3
[3 7 19 25 42]
[100 7 19 25 42] true

Functions that change the length (Compact, Insert, Delete) return the new slice: always assign the result back, as with append. slices.Reverse reverses in place. Sorting structs needs a comparison function, which returns a negative number, zero or a positive number:

go
package main

import (
	"cmp"
	"fmt"
	"slices"
)

type Player struct {
	Name  string
	Score int
}

func main() {
	words := []string{"go", "is", "fun"}
	slices.Reverse(words)
	fmt.Println(words)

	players := []Player{{"Asha", 88}, {"Ravi", 95}, {"Lee", 72}, {"Mira", 95}}
	slices.SortStableFunc(players, func(a, b Player) int {
		return cmp.Compare(b.Score, a.Score)   // highest first
	})
	fmt.Println(players)
}
Output
[fun is go]
[{Ravi 95} {Mira 95} {Asha 88} {Lee 72}]

2D slices

go
package main

import "fmt"

func main() {
	rows, cols := 3, 4
	grid := make([][]int, rows)
	for r := range grid {
		grid[r] = make([]int, cols)
		for c := range grid[r] {
			grid[r][c] = r * c
		}
	}
	for _, row := range grid {
		fmt.Println(row)
	}
}
Output
[0 0 0 0]
[0 1 2 3]
[0 2 4 6]

Maps

A map stores key → value pairs with fast lookup:

go
package main

import "fmt"

func main() {
	ages := map[string]int{"Asha": 31, "Ravi": 28}
	ages["Lee"] = 35               // add or update
	fmt.Println(ages["Asha"], len(ages))

	fmt.Println(ages["Nobody"])    // missing key → zero value

	age, ok := ages["Nobody"]      // "comma ok": was it really there?
	fmt.Println(age, ok)
	if a, ok := ages["Lee"]; ok {
		fmt.Println("Lee is", a)
	}

	delete(ages, "Ravi")
	fmt.Println(ages)               // fmt prints maps sorted by key
}
Output
31 3
0
0 false
Lee is 35
map[Asha:31 Lee:35]
  • Reading a missing key gives the zero value, not an error. Use v, ok := m[k] to tell "missing" apart from "present with value 0".
  • fmt prints maps sorted by key (handy for debugging), but range over a map is in random order.
  • A nil map (from var m map[string]int) can be read but panics on write. Create maps with a literal or make(map[string]int).

Counting and grouping

go
package main

import (
	"fmt"
	"maps"
	"slices"
	"strings"
)

func main() {
	text := "the cat and the hat and the bat"
	counts := map[string]int{}
	for _, w := range strings.Fields(text) {
		counts[w]++                  // missing keys start at 0
	}

	keys := slices.Sorted(maps.Keys(counts))   // sort keys for a stable order
	for _, k := range keys {
		fmt.Printf("%-4s %d\n", k, counts[k])
	}

	byLetter := map[byte][]string{}
	for _, w := range keys {
		byLetter[w[0]] = append(byLetter[w[0]], w)
	}
	fmt.Println(byLetter['t'], byLetter['a'])
}
Output
and  2
bat  1
cat  1
hat  1
the  3
[the] [and]

maps.Keys returns an iterator over the keys and slices.Sorted collects and sorts them: the standard way to loop over a map in a predictable order.

Sets

Go has no set type; a map to struct{} (which takes no memory) or bool does the job:

go
package main

import "fmt"

func main() {
	seen := map[string]struct{}{}
	for _, email := range []string{"a@x.com", "b@x.com", "a@x.com"} {
		if _, dup := seen[email]; dup {
			fmt.Println("duplicate:", email)
			continue
		}
		seen[email] = struct{}{}
	}
	fmt.Println(len(seen), "unique")
}
Output
duplicate: a@x.com
2 unique

⚠️ Maps aren't safe for use from several goroutines at once if any of them writes. You'll learn the fixes (a mutex, or sync.Map) in Goroutines and channels.

Practice

  1. Write func unique(nums []int) []int that returns the values without duplicates, in their original order.
  2. Read a sentence and print each word with its count, most frequent first.
  3. Show that changing a sub-slice changes the original, then fix it with slices.Clone.
  4. Group a list of people by city into a map[string][]string and print the cities in alphabetical order.
✎ Check your understanding

1.What does s[1:3] contain for s := []int{10, 20, 30, 40}?

2.Why must you write s = append(s, x)?

3.What does m["missing"] return for a map[string]int?

4.What's the iteration order of for k := range m?

← Functions