To get the first N items from a vector in Rust, you can use array slicing.
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;
// Retrieve the first N items from the vector
let first_n_items = &vector[0..n];
// Print the first N items
println!("{:?}", first_n_items);
}
[1, 2, 3, 4, 5]
In this example,
fn main() {
// Define a vector containing strings
let string_vector = vec!["apple", "banana", "orange", "grape", "kiwi"];
// Specify the range to retrieve the first three items
let range = 0..3;
// Retrieve the first three items from the string vector
let first_three_items = &string_vector[range];
// Print the first three items
println!("{:?}", first_three_items);
}
["apple", "banana", "orange"]
In this tutorial, we learned How to get First N Items from a Vector in Rust language with well detailed examples.