Curriculum Collections Arrays vs slices
Arrays vs slices
Go has fixed-size arrays ([N]T) and dynamically-sized slices ([]T). You almost always want slices. A slice is a view over a backing array — three machine words: pointer, length, capacity. append grows it; make pre-sizes it. The mental model is closer to Rust's Vec than to TS's Array.
Exercises
11 ready
01
pick one
Translate this TypeScript to idiomatic Go. The collection should
02
pick one
TypeScript tuples lock the length into the type. Pick the Go form
03
pick one
TypeScript needs .fill(0) to actually populate the array.
04
pick one
Pre-allocate room for many entries but start *empty*, so the
05
fill blanks
Translate ${name}.push(${value}) to idiomatic Go. The built-in
06
fill blanks
Translate xs.slice(0, 3) and xs.slice(3) to idiomatic Go.
07
type one line
Slicing in Go returns a *view* over the same backing array —
08
type one line
In TypeScript, passing an array to a function shares it — the
09
write a program
Write evens(n int) []int that returns the first n non-negative
10
write a program
Slices have no methods in Go. The operations TS devs reach for
11
type one line
Sort xs in place, then find the index of 7. The program prints