Stage 1 · Code
Functions & Composite Types
Arrays & Slices
Understand Go's two sequence types: fixed-size arrays and the dynamic slices that make everyday list work fast and safe.
Arrays
An array is a fixed-length sequence of elements of the same type. The length is part of the type: [3]int and [5]int are different types. Arrays are passed by value — a function receives its own copy.
In most Go code you will work with slices, not arrays. Arrays are the underlying storage mechanism that slices sit on top of. Knowing arrays helps you understand what slices are doing under the hood.
Slices
A slice is a descriptor with three fields: a pointer to an underlying array, a length, and a capacity. Slices are reference types — multiple slices can share the same underlying array.
append, len, cap
append adds elements to a slice and returns the new slice. When the underlying array has no room, append allocates a larger array and copies the data. Always capture the returned slice.
append may or may not return the same slice header depending on whether reallocation happened. If you call append(s, x) without capturing the result into s, you silently discard the new element. Always write s = append(s, x).
Slicing Expressions
A slicing expression s[low:high] produces a new slice that shares the same underlying array as s. Modifying elements through one slice affects the other.
copy
copy(dst, src) copies elements from src into dst and returns the number of elements copied (the minimum of the two lengths). After copying, dst and src are independent — changes to one do not affect the other.
| Operation | Creates new array? | Independent? |
|---|---|---|
Slice expression s[a:b] | No | No — shares underlying array |
copy(dst, src) | No (dst must already exist) | Yes — independent after copy |
append beyond capacity | Yes | Yes — new backing array allocated |
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.