如何初始化一个数组,使每个元素以编程方式不同(不是手动指定所有元素)?
似乎应该有一些方法可以通过关闭来实现,例如:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
更新: 这可以不使用"不安全"吗?
erikt从一年多前开始就有一个基于宏的答案看起来很有希望,但依赖宏观系统的迭代反引号扩展似乎并不存在......语言是否已改变以使其现在成为可能?