Dev Notes

Software Development Resources by David Egan.

Arrays and Slices in Rust


Rust
David Egan

Basic cheatsheet for Rust arrays and slices.

A rust array is a stack-allocated list of objects of a set type and fixed length.

Initialise:

// Arrays in rust are fixed length.
// Specify type and length in square brackets to initialize.
let arr: [i32; 5] = [1, 2, 3, 4, 5];

The correct data type and array length are now fixed and expected.

To print an array use Debug print:

println!("{:?}", arr);

Dereferencing

Dereference elements in the “universal” way:

for i in 0..arr.len() {
  println!("arr[{}] is {}", i, arr[i]);
}

Mutable Arrays

Arrays elements can be mutable, but the array length and data type is fixed:

let mut arr_to_change: [i32; 5] = [1, 2, 3, 4, 5];

arr_to_change[2] = 42;

Iteration

Arrays are not iterable. To iterate over each element, convert an array to iterator by calling .iter(), a slice method:

for el in arr.iter() {
  println!("{}", el);
}

Otherwise you could make a slice from the array:

for el in &arr {
	if Some(el) == arr.first() {print!("first! ")}
	println!("sliced: {}", el);
}

Enumerate the loop iterator to track an index:

for (i, el) in arr_to_change.iter().enumerate() {
  if i > 0 {print!(", ")};
  print!("{}", el);
}
println!();

If you try to access array elements that are out-of-bounds, Rust will “panic” - the programme terminates immediately. This prevents buffer overread bugs.

Memory Allocation

Get memory allocated:

println!("Array arr is {} bytes", std::mem::size_of_val(&arr));

Slices

Slices are a view into a block of memory represented by a pointer and a length. In other words, a slice is a view into an array.

Make a slice from the full array:

let sl: &[i32] = &arr;
println!("sl is {:?}", sl);

Make a slice of elements 0 and 1 - [0..2] is exclusive of the upper bound:

let sl2 = &arr[0..2];
// or overtly set the type:
let sl2: &[i32] = &arr[0..2];
println!("sl2 is {:?}", sl2);

Access Slice Elements

The get() method returns an element of a slice at the given index as an Option. In the example above, sl2.get(2) returns None because there is no element at that index - this prevents failure if the index is out of bounds.

get() uses Option to give type-safe bound checking array access.

Note that if you unwrap() an Option type that has a None value, the programme panics.

let i = 0;
let val = sl2.get(i);
if val != None {
  println!("sl2.get({}) returns {:?}", i, val.unwrap());
} else {
  // `val.unwrap()` at this point causes a panic.
  println!("Nothing at index {}. Move along.", i);
}

// Return an option
println!("sl2.get(1) returns {:?}", sl2.get(1));

// Unwrap the returned value
println!("sl2.get(1) returns {:?}", sl2.get(1).unwrap());
}

Resources


comments powered by Disqus