Code Example Template
Deep-Dive System Documentation
Contiguous Primitives: Arrays and Slices
In Rust, arrays and slices represent contiguous sequences of elements in memory.
1. Array ([T; N])
An array is a fixed-size sequence of elements of a single type T allocated continuously on the stack. The size N is a compile-time constant, making it incredibly performant.
let keys: [u32; 3] = [0x41, 0x42, 0x43]; // Stack allocation of 12 bytes
2. Slice (&[T])
A slice is a dynamically sized view into a contiguous sequence of elements. It is a fat pointer containing two elements: a pointer to the start of the sequence and the slice's length.
let view: &[u32] = &keys[1..3]; // Pointing to elements [0x42, 0x43]
Useful Methods
.len() -> usize
Returns the number of elements in the array or slice.
let arr = [10, 20, 30];
assert_eq!(arr.len(), 3);
.is_empty() -> bool
Returns true if the slice has a length of 0.
let arr: [i32; 0] = [];
assert!(arr.is_empty());
.contains(&x) -> bool
Returns true if the slice contains an element equal to the query.
let arr = [0x41, 0x42, 0x43];
assert!(arr.contains(&0x42));
.iter() -> Iter<'_, T>
Returns an iterator over the elements in the array/slice, yielding immutable references.
let arr = [1, 2, 3];
for val in arr.iter() {
println!("{}", val);
}
Quick Reference Guide
let arr: [i32; 4] = [1, 2, 3, 4];
let slice: &[i32] = &arr[1..3];