'Print last element of vector [duplicate]
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?
Solution 1:[1]
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");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stargateur |
