Search code examples
arraysrustuser-inputrust-cargo

How to create a custom sized array with user input in Rust?


This is my first time ever using Rust, so I know nothing about it. I know it's not ideal putting these prompts in the main, but I have plans to use the same user input for other functions as well. My goal is to create an array that's half empty and half full of randomly generated integers. I also need to be able to insert, remove, or find any integer in this array. To do this I want to prompt the user for an integer that will represent the size of the array and then prompt them again if they would like to insert, remove, or find an integer within that array.

The problem I am running into is when passing f_size to the array_set function. It says that the array_set parameter, size must be a const variable. What am I doing wrong?

fn main() {
 
    // String to store user's max key value
    let mut max_key = String::new();

    // Prompt user for max key value
    println!("Enter the desire size of your array:");

    // Read user input
    io::stdin().read_line(&mut max_key).expect("error");

    // Turn user input into integer
    let f_size: i32 = max_key.trim().parse().expect("not a number");

    // Store user's desired command
    let mut command = String::new();

    // Ask what action they want to perform
    println!("Enter insert, remove, or find");

    // Read user input
    io::stdin().read_line(&mut command).expect("error");


    // Call method to fill array with random numbers and perform the action
    array_set(f_size, command);

}


fn array_set(size: i32, command: String){
   // Random number generator
   let mut rng = rand::thread_rng();

   // Initialize empty array of user defined size
   let mut arr: [i32; size] = [0; size-1];

   // Loop through array and insert random values 
   for i in 0..size/2 {
        let num: i32 = rng.gen();
        arr.push(num);

    }

    arr;
}

Solution

  • With some small changes, your code compiles:

    • Use Vec instead of arrays; the size of an array is fixed at compile time. Vecs are the dynamically sized version of them.
    • Use usize instead of i32 for sizes - Rust needs all sizes to be usize.
    use rand::Rng;
    use std::io;
    
    fn main() {
        // String to store user's max key value
        let mut max_key = String::new();
    
        // Prompt user for max key value
        println!("Enter the desire size of your array:");
    
        // Read user input
        io::stdin().read_line(&mut max_key).expect("error");
    
        // Turn user input into integer
        let f_size: usize = max_key.trim().parse().expect("not a number");
    
        // Store user's desired command
        let mut command = String::new();
    
        // Ask what action they want to perform
        println!("Enter insert, remove, or find");
    
        // Read user input
        io::stdin().read_line(&mut command).expect("error");
    
        // Call method to fill array with random numbers and perform the action
        array_set(f_size, command);
    }
    
    fn array_set(size: usize, command: String) {
        // Random number generator
        let mut rng = rand::thread_rng();
    
        // Initialize empty array of user defined size
        let mut arr = vec![0; size];
    
        // Loop through array and insert random values
        for i in 0..size / 2 {
            let num: i32 = rng.gen();
            arr.push(num);
        }
    
        arr;
    }
    

    Whether or not the code makes sense will be seen once you try to use it.

    I can already tell, though, that you probably don't want to .push() all the time additional to initializing it with zeros before. That doesn't insert the values, it appends them. But that of course depends on your usecase.