How to get vector length in Rust
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.
Code example
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());}
Code explanation
Line 2: We use
Vec:new()to create a vector calledfleet, which accepts only string values usingVec<&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 thefleetvector.Line 8:
fleet.len()display the length of the vector or the number of values in the vector.