Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more idiomatic way to initialize an array with random numbers than a for loop?

Tags:

rust

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();
}
like image 460
SquattingSlavInTracksuit Avatar asked Mar 20 '18 15:03

SquattingSlavInTracksuit


1 Answers

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:

  • How can I initialize an array using a function?
  • What is the proper way to initialize a fixed length array?
like image 149
Shepmaster Avatar answered Oct 18 '22 11:10

Shepmaster