To get the last element in a vector in Rust, you can use the pop()
method or array indexing.
In this example,
numbers
with some elements.pop()
method to remove and return the last element of the vector, which gives us the last number.fn main() {
let mut numbers = vec![1, 2, 3, 4, 5];
let last_number = numbers.pop().unwrap();
println!("Last number is: {}", last_number);
}
Last number is: 5
In this example,
fruits
with some elements.fruits[fruits.len() - 1]
and store it in the variable last_fruit
.fn main() {
let fruits = vec!["apple", "banana", "cherry"];
let last_fruit = fruits[fruits.len() - 1].to_string();
println!("Last fruit is: {}", last_fruit);
}
Last fruit is: cherry
In this tutorial, we learned How to get Last Element in Array in Rust language with well detailed examples.