1

In Rust, I have seen that we can use the .last() function to access the last element of a vector. However, when I try to interpolate this into print output like so

fn main() {
    let mut v: Vec<f64> = Vec::new();
    v.push(1.0); v.push(1.9); v.push(1.2);
    println!("Last element is {}", v.last());    // (*)
}

I get the following error message:

error[E0277]: `Option<&f64>` doesn't implement `std::fmt::Display`

The full error text hints that I can use {:?} instead. If I change (*) to read println!("Last element is {:?}", v.last()); // (*), then the program prints

Last element is Some(1.2)

How can I just get Last element is 1.2?

How can I extract the value 1.2 as an f64?

Max
  • 695
  • 5
  • 18
  • If you know for sure there's at least 1 element, then just `v.last().unwrap()`. But if there are no items, the program will crash – Alexey S. Larionov Mar 11 '22 at 07:19
  • Aha, so would it be correct to think of the `Option<&f64>` type (that `last()` returns) as a union type that can contain either the float or a token saying that the vector is empty? – Max Mar 11 '22 at 07:21
  • 1
    Yes, except that it doesn't technically store a float `f64`, but a reference to float inside the vector `&f64` – Alexey S. Larionov Mar 11 '22 at 07:22

1 Answers1

7

There may or may not be a last element, depending if the Vector is empty or not.

You can check if the Option<f64> returned by last() is Some(val). This can be done using if let or match or other techniques (unwrap(), unwrap_or() etc.). For example:

fn main() {
    let v = vec![1.0, 1.9, 1.2];
    if let Some(val) = v.last() { 
        println!("Last element is {}", val);
    } else {
        println!("The vector is empty");
    }
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91
M.A. Hanin
  • 8,044
  • 33
  • 51