如何初始化一个数组,使每个元素以编程方式不同(不是手动指定所有元素)?
似乎应该有一些方法可以通过关闭来实现,例如:
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 real use case
// does not allow default values for the array elements...
let mut z: [usize; 10] = [0; 10];
for i in 0..10 {
z[i] = i;
}
}
更新:这可以在不使用“不安全”的情况下完成吗?
一年多前有一个基于宏的answer by erikt看起来很有希望,但依赖宏观系统的迭代反引号扩展似乎不存在......语言是否改为现在可以做到这一点吗?