19

Is there an idiomatic way of initialising arrays in Rust. I'm creating an array of random numbers and was wondering if there is a more idiomatic way then just doing a for loop. My current code works fine, but seems more like C than proper Rust:

let mut my_array: [u64; 8] = [0; 8];
for i in 0..my_array.len() {
    my_array[i] = some_function();
}
1
  • You may find this Q & A helpful. Basically you can use a list comprehension to initialize your array. Commented Mar 20, 2018 at 15:34

2 Answers 2

18

Various sized arrays can be directly randomly generated:

use rand; // 0.7.3

fn main() {
    let my_array: [u64; 8] = rand::random();
    println!("{:?}", my_array);
}

Currently, this only works for arrays of size from 0 to 32 (inclusive). Beyond that, you will want to see related questions:

Sign up to request clarification or add additional context in comments.

Comments

2

The other solution is nice and short, but does not apply to the case where you need to initialize an array of random numbers in a specific range. So, here's an answer that addresses that case.

use rand::{thread_rng, Rng};

fn main() {
    let a = [(); 8].map(|_| thread_rng().gen_range(0.0..1.0));
    println!("The array of random float numbers between 0.0 and 1.0 is: {:?}", a);
}

I would be happy to know if there's a better (shorter and more efficient) solution than this one.

1 Comment

This solves the problem for float but the OP was asking about u64; looks like all you need to do is change 0.0..1.0 to 0..5555 or whatever your desired range is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.