小编odd*_*boy的帖子

使用闭包初始化数组

如何初始化一个数组,使每个元素以编程方式不同(不是手动指定所有元素)?

似乎应该有一些方法可以通过关闭来实现,例如:

fn main() {
    let x: [u32; 10] = [0; 10];
    println!("{:?}", x);

    let mut count = 0;
    let mut initfn = || { let tmp = count; count += 1; tmp };

    // What I want below is a non-copying array comprehension -- one
    // which runs initfn() 10 times...  Is there such a thing?  Maybe
    // using iterators?
    let y: [u32; 10] = [initfn(); 10];
    println!("{:?}", y);

    // The goal is to avoid the following because my …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
0
解决办法
598
查看次数

标签 统计

rust ×1