Go - Arrays, Slices, Maps

Beginner 10/10 Teacher 10/10 Architect 10/10
Try it: Create a slice of three strings and append a fourth. Print length and contents.

Arrays

var a [3]int
b := [3]int{1,2,3}

Slices

s := []int{1,2,3}
s = append(s, 4)
sub := s[1:3] // shares backing array

Maps

m := map[string]int{"a":1}
m["b"] = 2
v, ok := m["c"] // ok=false if missing

Gotchas

  • Slices share backing arrays; copying vs referencing matters.
  • Maps are reference types; reading missing keys yields zero value with ok=false.

Common errors

  • Confusing arrays with slices: arrays have fixed length; slices are dynamic views over arrays.
  • Modifying a subslice affects the original due to shared backing array.

Practice

  • Given s := []int{1,2,3}, create t := s[1:] and change t[0]. Inspect s and t.

Quick quiz

  1. How do you check if a key exists in a map?
Show answer v, ok := m[key]ok is false if missing.