In Rust, the vector is a fundamental data structure provided by the standard collection library. It serves as a dynamic array that can store values of the same data type.
To get the length of a vector in Rust, the len()
method is used. It returns a number from 0
to the maximum value depending on the content of the vector.
Let's see the following code example to get the length of the vector.
fn main() {let mut fleet : Vec<&str> = Vec::new();fleet.push("Ford");fleet.push("Bentley");fleet.push("Jeep");println!("{:?}", fleet);println!("Number Of Cars : {}", fleet.len());}
Line 2: We use Vec:new()
to create a vector called fleet
, which accepts only string values using Vec<&str>
.
Lines 3–5: We add cars (values) to the fleet (vector) using fleet.push("value")
.
Line 7: We use {:?}
to display all the values of the fleet
vector.
Line 8: fleet.len()
display the length of the vector or the number of values in the vector.