Sub topic 1
Contiguous storage: arrays and vectors
Slices only make sense once you know what they point at. A slice is a view into a run of values stored side by side in memory. This chapter covers the two main owners of such runs: arrays and vectors. The next chapters build slices on top of them.
Prerequisites
This chapter assumes you already know the following:
- Basic Rust syntax:
let, functions,println!, andforloops. - Ownership and moves: a value has one owner, and assigning a non-
Copyvalue moves it. - References and the basics of borrowing:
&T,&mut T, and the rule that you cannot mutate a value while a shared reference to it is alive. - A first look at
[T; N]andVec<T>. You do not need to be fluent with them yet.
What "contiguous" means
Contiguous storage means the elements of a collection sit one after another in memory, with no gaps and no pointers between them. If an element of type T takes size_of::<T>() bytes, then element i lives at:
start_address + i * size_of::<T>()This formula is why indexing is fast. Reading a[i] costs one multiplication, one addition, and one memory read. It does not depend on how long the collection is. It is also why a slice can be so small. To describe a stretch of contiguous elements, you only need a start address and a length.
You can check the layout yourself by printing the distance between neighbouring elements:
fn main() {
let a = [10u32, 20, 30];
let p0 = &a[0] as *const u32 as usize;
let p1 = &a[1] as *const u32 as usize;
let p2 = &a[2] as *const u32 as usize;
println!("{} {}", p1 - p0, p2 - p1);
}This prints 4 4. A u32 is four bytes, and the elements are exactly four bytes apart.
Arrays: fixed length, length in the type
An array has the type [T; N]. T is the element type and N is the number of elements. N must be known at compile time. The length is part of the type, so [i32; 3] and [i32; 4] are different types.
fn main() {
let a: [i32; 5] = [10, 20, 30, 40, 50];
let zeros = [0u8; 8]; // repeat syntax: eight copies of 0
println!("{} {}", a.len(), zeros.len());
println!("{}", std::mem::size_of_val(&a));
println!("{}", std::mem::size_of::<[u8; 8]>());
}The output is:
5 8
20
8Five i32 values take 20 bytes. An array has no hidden header and no extra fields, so its size is N * size_of::<T>().
An array is stored inline, wherever the variable lives. A local array lives on the stack. An array inside a struct is part of that struct's memory. An array inside a Box lives on the heap. Arrays do not allocate on their own.
Arrays are values
Arrays follow the same ownership rules as other types, with one useful twist. If T is Copy, then [T; N] is Copy too. Passing such an array to a function copies every element.
fn bump(mut a: [i32; 3]) -> [i32; 3] {
a[0] += 1;
a
}
fn main() {
let original = [1, 2, 3];
let changed = bump(original);
println!("{:?} {:?}", original, changed);
}This prints [1, 2, 3] [2, 2, 3]. The caller's array is untouched because the function received a copy. For three integers this is cheap. For [u8; 1_000_000] it is a million-byte copy on every call, and you would normally pass a reference instead. A reference to an array can also be viewed as a slice, which is where this tutorial is heading.
Common array errors
- Length mismatch.
let a: [i32; 3] = [1, 2, 3, 4];fails to compile because the types differ. The compiler reports "expected an array with a size of 3, found one with a size of 4". - Non-constant length.
let n = 4; let a = [0; n];fails becausenis a variable, not a constant. Useconst N: usize = 4;, or use aVec. - Indexing with a non-
usize. Indices must beusize. Ani32index is a type error. Convert it withas usizeorusize::try_from. - Moving out by index.
let s = names[0];fails whennamesis an array ofString, because you cannot move one element out of an array through an index. Borrow with&names[0], or clone it. - Large arrays on the stack. The stack is small, often a few megabytes for the main thread. A very large array can overflow it. Put the data in a
Vecor aBox<[T]>.
Vectors: growable, heap-allocated
Vec<T> is an owned, growable sequence. The elements are stored contiguously on the heap. The Vec value itself is a small header of three words:
- A pointer to the start of the heap buffer.
- The capacity: how many elements the buffer has room for.
- The length: how many of those slots are currently filled.
Only the first len slots hold valid values. The remaining capacity - len slots are reserved but uninitialised, and safe code cannot read them.
fn main() {
let mut v: Vec<i32> = Vec::with_capacity(4);
println!("len={} cap_ok={}", v.len(), v.capacity() >= 4);
let start = v.as_ptr();
for i in 0..4 {
v.push(i * 10);
}
println!("len={} same_buffer={}", v.len(), start == v.as_ptr());
}This prints:
len=0 cap_ok=true
len=4 same_buffer=trueVec::with_capacity(4) allocates room for four elements up front. Four pushes fit in that room, so the buffer address never changes. Rust documents that capacity() returns at least the requested amount, which is why the code tests >= 4 instead of == 4.
What happens when the buffer is full
When push finds len == capacity, the vector allocates a larger buffer, copies the elements across, and frees the old buffer. The growth is geometric, so the cost of reallocating is spread over many pushes. The exact growth factor is an implementation detail, so do not depend on it.
The reallocation has an important consequence. Pushing can move every element to a new address. Any pointer or reference into the old buffer would dangle. Rust prevents this at compile time through borrowing. Take a reference to an element and then call push while that reference is still used later, and the compiler rejects the program with error E0502 ("cannot borrow v as mutable because it is also borrowed as immutable"). The fix is to finish with the reference first, or to copy the value out:
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0]; // copies an i32; no borrow of v remains
v.push(first + 10);
println!("{:?}", v);
}This prints [1, 2, 3, 11]. The same rule is how the borrow checker keeps slices safe. A slice borrows from its owner, so the owner cannot be resized while the slice is alive.
Growing and shrinking
| Method | Effect |
|---|---|
| `push(x)` | Appends one element. May reallocate. |
| `pop()` | Removes and returns the last element as `Option<T>`. Never shrinks the buffer. |
| `insert(i, x)` | Inserts at `i`, shifting later elements right. Cost grows with the number of elements shifted. |
| `remove(i)` | Removes at `i`, shifting later elements left. Panics if `i >= len`. |
| `clear()` | Drops all elements and sets `len` to 0. The capacity stays. |
| `reserve(n)` | Ensures room for `n` more elements, in one allocation. |
| `shrink_to_fit()` | Asks to release unused capacity. |
Because storage is contiguous, inserting or removing in the middle is not free. The elements after the position must be moved. If you only add and remove at the end, every operation is cheap. If you need frequent insertions at the front, consider VecDeque.
Arrays and vectors compared
| Property | `[T; N]` | `Vec<T>` |
|---|---|---|
| Length | Fixed, part of the type | Changes at run time |
| Where the elements live | Inline, wherever the array is placed | Always on the heap |
| Size of the value itself | `N * size_of::<T>()` | Three words, regardless of length |
| Allocates | No | Yes, once non-empty |
| `Copy` | Yes, if `T` is `Copy` | Never. It owns a heap buffer. |
| Indexing | `a[i]`, bounds-checked | `v[i]`, bounds-checked |
Both give the same view of the data: a start address plus a run of T values. That shared view is what a slice captures. A function that only needs to read or modify elements does not care whether they came from an array or a vector.
Indexing and bounds
Both types support a[i]. Rust checks the index against the length on every access. If the index is out of range, the program panics:
fn main() {
let v = vec![1, 2, 3];
let i = v.len(); // 3 is one past the last valid index
println!("{}", v[i]); // panics: index out of bounds: the len is 3 but the index is 3
}With a literal index into an array, such as a[7] on a five-element array, the compiler can often reject the program. With an index computed at run time, the panic happens when the code runs. Panicking is the safe outcome, because it never reads memory outside the buffer. The chapter on bounds checking shows how get returns an Option instead.
Converting between arrays and vectors
Moving data between the two types always involves a copy or a move into a new location, because an array lives inline and a vector lives on the heap.
fn main() {
let a = [1, 2, 3];
let v = Vec::from(a); // array -> Vec: elements are moved to the heap
let back: [i32; 3] = v.try_into().unwrap(); // Vec -> array: length is checked
println!("{:?}", back);
let w = vec![1, 2, 3, 4];
let r: Result<[i32; 3], _> = w.try_into();
println!("{:?}", r);
}This prints:
[1, 2, 3]
Err([1, 2, 3, 4])Going from Vec<T> to [T; N] can fail, because the vector's length is only known at run time. try_into returns Err containing the original vector when the length differs from N. The vector is handed back to you, not dropped.
A few other ways to build a vector are worth knowing:
vec![1, 2, 3]builds a vector from a list.vec![0; 100]builds a vector of 100 zeros. The element type must beClone.a.to_vec()copies an array's elements into a new vector. This method is defined on slices, which you will meet in the next chapter.
Why this matters for slices
Three facts from this chapter carry forward:
- Elements sit side by side, so any stretch of them can be described by a start address and a count.
- An array's length is in its type, and a vector's length is a run-time value. A single type that covers both has to carry its length at run time.
- A vector's buffer can move when it grows, so anything that points into it must stop being used before the vector changes.
A slice, written &[T], is exactly that: a borrowed start address and a length, valid for the duration of the borrow. The next chapter introduces it.
Exercise
Given let mut v = Vec::with_capacity(3); v.push(1); v.push(2);, what are v.len() and the smallest value v.capacity() can have? If you then take let r = &v[0];, call v.push(3), and afterwards print r, does the program compile? Explain why that rule exists.
Show answer
v.len() is 2, and v.capacity() is at least 3. The program does not compile. r is a shared borrow of v that is still used after the push, and push needs a mutable borrow, so the compiler reports E0502. The rule exists because push can reallocate the buffer when len == capacity, which would leave r pointing at freed memory. Here the third push would fit in the existing capacity, but the compiler checks types and borrows, not the actual capacity, so it rejects the code either way.
Exercise
Why does let b: [i32; 4] = [1, 2, 3]; fail to compile, while let r: Result<[i32; 4], _> = vec![1, 2, 3].try_into(); compiles and returns Err?
Show answer
An array's length is part of its type and is checked at compile time, so a three-element literal cannot have the type [i32; 4]. A vector's length is only known at run time, so converting it to an array can only be checked when the program runs. The conversion is written as try_into, which returns Err carrying the original vector when the lengths differ.