Sub topic 1
Contiguous storage: arrays and vectors
Prerequisites
This chapter assumes you know:
- Basic Rust syntax: variables, functions, and
println!. - Ownership and moves.
- The basics of references and borrowing.
- How to write an array literal and call
Vec::neworvec!.
Slices are views into memory that is laid out in a line. Before you can borrow part of a collection, you need a clear picture of what that memory looks like. This chapter builds that picture.
What "contiguous" means
Contiguous storage means that the elements of a collection sit next to each other in memory, with no gaps. Element 0 comes first, element 1 starts right where element 0 ends, and so on. Both [T; N] (an array) and Vec<T> (a vector) store their elements this way.
Contiguity gives you two properties:
- Constant-time indexing. The address of element
iisstart + i * size_of::<T>(). No search is needed. - Cache-friendly iteration. Walking the elements in order reads memory in order, which CPUs handle well.
You can check this yourself:
use std::mem::size_of;
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!("gap 0->1: {} bytes", p1 - p0);
println!("gap 1->2: {} bytes", p2 - p1);
println!("size_of::<u32>() = {}", size_of::<u32>());
}Each gap equals size_of::<u32>(), which is 4 bytes. The elements are packed tightly.
Arrays: fixed size, usually on the stack
An array has the type [T; N]. The length N is part of the type and must be known at compile time. [i32; 3] and [i32; 4] are different types.
fn main() {
let a: [i32; 5] = [10, 20, 30, 40, 50];
let zeros = [0u8; 8]; // eight zero bytes
println!("{} {}", a.len(), zeros.len());
println!("first = {}, last = {}", a[0], a[a.len() - 1]);
}A local array lives directly in the stack frame, with no separate allocation. Its size never changes. You can't push to it or remove from it.
Vectors: growable, with a heap buffer
A Vec<T> owns a buffer on the heap and can grow. Internally it holds three values:
- a pointer to the start of the buffer,
- a length: how many elements are in use,
- a capacity: how many elements the buffer can hold before it must grow.
The Vec value itself is small and fixed in size. Only the buffer it points to is large.
The next program shows length and capacity:
fn main() {
let mut v: Vec<i32> = Vec::with_capacity(4);
println!("len={} cap>=4: {}", v.len(), v.capacity() >= 4);
v.push(1);
v.push(2);
v.push(3);
println!("len={} cap>=4: {}", v.len(), v.capacity() >= 4);
v.extend([4, 5]); // exceeds the original capacity
println!("len={} cap>=5: {}", v.len(), v.capacity() >= 5);
}When a push needs more room than the capacity allows, the Vec allocates a larger buffer, copies the elements over, and frees the old buffer. The elements may end up at a new address. This is why Rust won't let you hold a reference into a Vec while you push to it. A later chapter covers that rule in detail.
Comparing the two
| Property | Array `[T; N]` | Vector `Vec<T>` |
|---|---|---|
| Length | Fixed, part of the type | Changes at run time |
| Element storage | Inline, often on the stack | Heap buffer |
| Can push or remove | No | Yes |
| Owns its elements | Yes | Yes |
| Contiguous | Yes | Yes |
The last two rows matter most for this tutorial. Both types own their data, and both keep it in one contiguous block. Because the layout is the same, one kind of reference can point into either: a view of "some number of Ts in a row". That view is the slice.
Common mistakes
- Treating the length as part of every sequence type. Only arrays carry
Nin the type. A function that takes[i32; 3]rejects a[i32; 4]. - Confusing
lenwithcapacity. Indexing is checked againstlen, notcapacity. Spare capacity is not readable. - Assuming a
Vec's elements stay at one address. Any operation that grows the buffer can move them.
Exercise
You create let mut v = Vec::with_capacity(10); and push three i32 values. What are v.len() and v.capacity(), and why is v[5] still invalid?
Show answer
v.len() is 3 and v.capacity() is at least 10. Indexing is checked against the length, not the capacity. Positions 3 to 9 are allocated but hold no initialized elements, so v[5] panics.
Exercise
Why are [i32; 3] and [i32; 4] different types, and what does that mean for a function that takes [i32; 3]?
Show answer
The length N is part of an array's type. A function declared with [i32; 3] accepts only arrays of exactly three elements, so passing a [i32; 4] is a compile-time error.