To get the last item in a vector in Rust, you can use the last
method provided by the Vec
type.
In this example,
vec
with a series of integer values using the vec!
macro.last
method on the vector vec
to get an Option
that contains the last element of the vector.last
method returns Some(&T)
if the vector is not empty, where &T
is a reference to the last element. If the vector is empty, it returns None
.match
expression to handle both cases: if last
returns Some(&last_item)
, we print the last item to the console; if it returns None
, we print a message indicating that the vector is empty.fn main() {
let vec = vec![10, 20, 30, 40, 50];
match vec.last() {
Some(&last_item) => println!("The last item is: {}", last_item),
None => println!("The vector is empty"),
}
}
The last item is: 50
In this example,
vec
with a series of string values using the vec!
macro.last
method on the vector vec
to get an Option
that contains the last element of the vector.last
method returns Some(&String)
if the vector is not empty, where &String
is a reference to the last element. If the vector is empty, it returns None
.match
expression to handle both cases: if last
returns Some(last_item)
, we print the last item to the console; if it returns None
, we print a message indicating that the vector is empty.fn main() {
let vec = vec!["apple", "banana", "cherry", "date", "elderberry"];
match vec.last() {
Some(last_item) => println!("The last item is: {}", last_item),
None => println!("The vector is empty"),
}
}
The last item is: elderberry
In this tutorial, we learned How to get Last Item in a Vector in Rust language with well detailed examples.