How to get vector length in Rust (2024)

Table of Contents
Code example Code explanation

Trusted answers to developer questions

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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 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.

RELATED TAGS

rust

Did you find this helpful?

How to get vector length in Rust (2024)
Top Articles
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 6216

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.