To get the last N items from a vector in Rust, you can use array slicing in combination with the length of the vector.
In this example,
fn main() {
// Define a vector containing elements
let vector = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Specify the number of items to retrieve (N)
let n = 5;
// Calculate the starting index for the last N items
let start_index = vector.len() - n;
// Retrieve the last N items from the vector
let last_n_items = &vector[start_index..];
// Print the last N items
println!("{:?}", last_n_items);
}
[6, 7, 8, 9, 10]
In this example,
fn main() {
// Define a vector containing strings
let string_vector = vec!["apple", "banana", "orange", "grape", "kiwi"];
// Calculate the starting index for the last three items
let start_index = string_vector.len() - 3;
// Retrieve the last three items from the string vector
let last_three_items = &string_vector[start_index..];
// Print the last three items
println!("{:?}", last_three_items);
}
["orange", "grape", "kiwi"]
In this tutorial, we learned How to get Last N Items from a Vector in Rust language with well detailed examples.