Arrays & Slices
Array
An array is a collection of objects of the same type
T
, stored in contiguous memory.Arrays are created using brackets
[]
, and their length, which is known at compile time, is part of their type signature[T; length]
.Arrays are stack allocated.
Arrays own their data.
Arrays can be automatically borrowed as slices.
let m = [1, 2, 3]; // Rust will infer the type and length let n: [i32; 3] = [1, 2, 3];
Slice
Slices are similar to arrays, but their length is not known at compile time.
Slices are views into data; they do not own the data.
Slices are references and follow Rust's borrowing rules.
Slices are a fat pointer:
A reference to the start of the data.
The length of the slice.
let x = [1, 2, 3]; let slice = &x[1..]; // A slice starting from index 1
Reference
Last updated