generate a random array in rust

To generate a random array in Rust, you can use the rand crate to generate random numbers and the arrayvec crate to create a dynamic array.

Here's an example code snippet that generates an array of random i32 numbers using the thread_rng random number generator:

main.rs
extern crate rand;
extern crate arrayvec;

use rand::{thread_rng, Rng};
use arrayvec::ArrayVec;

fn main() {
    let mut rng = thread_rng();
    let mut arr = ArrayVec::<[i32; 10]>::new(); // create a dynamic array of length 10

    for _ in 0..10 {
        arr.push(rng.gen_range(0, 100)); // generate a random number between 0 and 100 and push it to the array
    }

    println!("{:?}", arr);
}
398 chars
17 lines

In this example, we first import the necessary crates, rand and arrayvec. We then create a new instance of the thread_rng random number generator.

Next, we create a new ArrayVec of size 10, which is a dynamically-sized array. We then generate 10 random numbers using the gen_range method of the random number generator, which generates a random number between the given minimum and maximum values (in this case, 0 and 100).

Finally, we push each generated number to the array using the push method. After generating and adding all the elements, we simply print the array using the println macro.

gistlibby LogSnag