To get the length of a vector in Rust, you can use the len
method of the Vec
class.
In this example,
std::vec::Vec
module, although it's included in the prelude and doesn't need to be explicitly imported.num_vector
with a set of numeric values using the vec![]
macro, which allows us to easily define vectors.len
method on num_vector
to get the number of elements in the vector. The len
method returns the length of the vector as a usize
value.len
method to a variable named num_vector_length
.println!
macro to display the value of num_vector_length
on the console.fn main() {
let num_vector = vec![10, 20, 30, 40, 50];
let num_vector_length = num_vector.len();
println!("Length of numeric vector: {}", num_vector_length);
}
Length of numeric vector: 5
In this example,
std::vec::Vec
module, although it's included in the prelude and doesn't need to be explicitly imported.str_vector
with a set of string values using the vec![]
macro. Each string value is defined using the String::from
function to convert string literals into String
objects.len
method on str_vector
to get the number of elements in the vector. The len
method returns the length of the vector as a usize
value.len
method to a variable named str_vector_length
.println!
macro to display the value of str_vector_length
on the console.fn main() {
let str_vector = vec![String::from("apple"), String::from("banana"), String::from("cherry")];
let str_vector_length = str_vector.len();
println!("Length of string vector: {}", str_vector_length);
}
Length of string vector: 3
In this tutorial, we learned How to Get Length of a Vector in Rust language with well detailed examples.