To get the first item in a vector in Rust, you can use indexing with the square brackets notation and specify the index 0.
In this example,
vec
with elements of a specific type, such as integers or strings.[]
to access the first item in the vector by specifying the index 0
.0
corresponds to the first item in Rust, as indexing starts from zero.fn main() {
let vec = vec![1, 2, 3, 4, 5];
let first_item = vec[0];
println!("First item in vector: {}", first_item);
}
First item in vector: 1
In this example,
str_vec
containing strings.[]
to access the first string in the vector by specifying the index 0
.0
represents the first string in Rust vectors.fn main() {
let str_vec = vec!["Hello", "World"];
let first_string = str_vec[0];
println!("First string in vector: {}", first_string);
}
First string in vector: Hello
In this tutorial, we learned How to get First Item in a Vector in Rust language with well detailed examples.