To access the first element of a vector or slice in Rust, you can use indexing with square brackets and the index 0.
In this example,
numbers
with numeric values.numbers[0]
and store it in a variable named first_element
.fn main() {
let numbers = vec![10, 20, 30, 40, 50];
let first_element = numbers[0];
println!("First element: {}", first_element);
}
First element: 10
In this example,
fruits
with string values.fruits[0]
and store it in a variable named first_fruit
.fn main() {
let fruits = vec!["Apple", "Banana", "Cherry", "Date"];
let first_fruit = fruits[0];
println!("First fruit: {}", first_fruit);
}
First fruit: Apple
In this tutorial, we learned How to get First Element in Array in Rust language with well detailed examples.