Collections & Loops
Go slices, maps, and iteration with range.
Arrays & Slices
Arrays have fixed size; slices are dynamic:
// Array (fixed)
var a [3]int // [0 0 0]
// Slice (dynamic)
s := []int{1, 2, 3}
s = append(s, 4) // [1 2 3 4]
// Make with capacity
s = make([]int, 0, 10) // len=0, cap=10
Slice operations
s := []int{1, 2, 3, 4, 5}
s[1:3] // [2 3]
len(s) // 5
Maps
m := map[string]int{"a": 1, "b": 2}
m["c"] = 3
value, ok := m["d"] // 0, false (not found)
delete(m, "a")
Make a map
m := make(map[string]int)
Loops
Go has only one loop construct: for.
Classic for
for i := 0; i < 10; i++ {
fmt.Println(i)
}
Range (collections)
// Slice
for i, v := range s {
fmt.Println(i, v)
}
// Map
for k, v := range m {
fmt.Println(k, v)
}
// Skip index or value
for _, v := range s { ... }
for i := range s { ... }
While-style
running := true
for running {
if done() {
running = false
}
}
break & continue
for i := 0; i < 10; i++ {
if i%2 == 0 {
continue
}
if i > 7 {
break
}
}
Next: String Manipulation