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.
11 ready
01
pick oneTranslate this TypeScript to idiomatic Go. The collection should
02
pick oneTypeScript 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 onePre-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 lineSlicing in Go returns a *view* over the same backing array —
08
type one lineIn 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 programSlices 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