有没有比 for 循环更惯用的方法来用随机数初始化数组? [英] Is there a more idiomatic way to initialize an array with random numbers than a for loop?

查看:39
本文介绍了有没有比 for 循环更惯用的方法来用随机数初始化数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rust 中是否有一种惯用的方法来初始化数组.我正在创建一个随机数数组,并想知道是否有更惯用的方法然后只做一个 for 循环.我当前的代码运行良好,但看起来更像 C 而不是适当的 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();
}

推荐答案

各种大小的数组可以直接随机生成:

use rand; // 0.7.3

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

目前,这只适用于大小从 0 到 32(含)的数组.除此之外,您还需要查看相关问题:

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

这篇关于有没有比 for 循环更惯用的方法来用随机数初始化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆