Return last n elements of vector in Rust without mutating the vector

You need to consider the case where the vector doesn't have two items.

I'd use iterator adapters like Iterator::rev and Iterator::take and then finish with Iterator::sum:

let sum = stored_nums.iter().rev().take(2).sum();
stored_nums.push(sum);

This allows you to avoid explicit handling of cases where the vector / slice / iterator is too short but the code still deals with it implicitly.


You could also directly index into the slice:

let len = stored_nums.len();
let sum = stored_nums[len - 1] + stored_nums[len - 2];
stored_nums.push(sum);

This will panic if there are less than 2 elements, however.

You could attempt to deal with the vector being too short in this case, but it's a bit verbose:

fn add_last_two(nums: &[u32]) -> Option<u32> {
    let len = nums.len();

    let idx_a = len.checked_sub(1)?;
    let idx_b = len.checked_sub(2)?;

    let a = nums.get(idx_a)?;
    let b = nums.get(idx_b)?;

    Some(a + b)
}

fn main() {
    let mut stored_nums: Vec<u32> = vec![0, 1];
    let sum = add_last_two(&stored_nums).unwrap_or(0);
    stored_nums.push(sum);
}

Note that it might be nicer to use a Fibonacci iterator and just collect that into a Vec.


You can use a reverse iterator on the Vec:

let (n1, n2) = {
    let mut rev_iter = stored_nums.iter().rev();
    (rev_iter.next().unwrap().clone(), rev_iter.next().unwrap().clone())
};
stored_nums.push(n1 + n2);

Tags:

Vector

Rust