Accessing the last element of a Vec or a slice

And just after posting the question, the answer appears to be obvious:

fn top (&mut self) -> Option<&f64> {
    match self.len() {
        0 => None,
        n => Some(&self[n-1])
    }
}

I.e. the usize was never the problem - the return type of top() was.


You can use slice::last:

fn top(&mut self) -> Option<f64> {
    self.last().copied()
}

Option::copied (and Option::cloned) can be used to convert from an Option<&f64> to an Option<f64>, matching the desired function signature.

You can also remove the mut from both the implementation and the trait definition.

Tags:

Vector

Rust