Creating a vector with capacity(number) : Variable as size

Greetings everyone,

I'm currently trying to create a Vector of Strings with a desired capacity.
This capacity is known when the users input a number.

But the compiler asks for a "usize" whereas I give it an i32.

What could be the solution ?

Here is my code :

// Test
use std::io;
use std::io::prelude::*;

fn main(){

    //Asking user to type in a number of elements
    print!("Number of elements : ");
    io::stdout().flush()
        .expect("");

    // Creating the number variable as a String in order to read it
    let mut number = String::new();
    // Reading input
    io::stdin().read_line(&mut number)
        .expect("Error : Failed to read user input");
    // Parsing input to an Integer 32 bits
    let number = number.trim().parse::<i32>()
        .expect("Error : Failed to convert number of elements to i32");

    // Creating a Vector of Strings in order to hold every names
    let mut elements_list : Vec<String> = Vec::new();
    //let mut elements_list : Vec<String> = Vec::with_capacity(number);

    //For loop for each element
    for i in 0..number{
        print!("Input name of element {} : ", i+1);
        io::stdout().flush()
            .expect("");
        // Reading element's name
        let mut element_name = String::new();
        io::stdin().read_line(&mut element_name)
            .expect("Error : Failed to read user input");
        
        //Removing the '\n' character
        element_name.pop();
        //Adding element_name to the vector of names
        elements_list.push(element_name);
    }

    //Printing the content of the vector
    for i in elements_list{
        println!("Element : {} ", i);
    }

}

Instead of this

let number = number.trim().parse::<i32>()
        .expect("Error : Failed to convert number of elements to i32");

Do this

let number = number.trim().parse::<usize>()
        .expect("Error : Failed to convert number of elements to usize");

Because you are only using number as an unsigned integer. Then you can use number to set the capacity of your Vec


Btw, to get syntax highlighting do this

```rust
```
2 Likes

Great ! Thank you for your answer it worked !

1 Like