Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

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

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...