有没有一种办法不必两次初始化数组? [英] Is there a way to not have to initialize arrays twice?
问题描述
我需要一个阵列的每个元素初始化为一个非恒定的恩pression。我可以这样做,而不必到阵列中的每个元素首先初始化一些相同的意义EX pression?下面是想我是能够做一个例子:
I need to initialize each element of an array to a non-constant expression. Can I do that without having to first initialize each element of the array to some same meaningless expression? Here's an example of what I'd like to be able to do:
fn foo(xs: &[int, ..1000]) {
let mut ys: [int, ..1000];
for (x, y) in xs.iter().zip(ys.iter_mut()) {
*y = *x / 3;
}
// ...
}
上面的code给出了编译时错误:结果使用可能未初始化的变量的:伊苏
要解决这个问题,我需要改变功能的第一行,象这样一些虚拟值来初始化 YS
的元素:
To fix the problem I need to change the first line of the function to initialize the elements of ys
with some dummy values like so:
let mut ys: [int, ..1000] = [42, ..1000];
有没有办法省略掉额外的初始化?包裹在一个不安全块一切似乎并没有任何区别。
Is there any way to omit that extra initialization? Wrapping everything in an unsafe block doesn't seem to make any difference.
推荐答案
使用的std ::纪念品::初始化
,即
let mut ys: [int, ..1000] = unsafe{std::mem::uninitialized()};
我不认为这是一个更安全的方式来做到这一点。问题是,固定大小的数组只是没有得到同样的爱为 VEC
拉斯特,因为他们不能实施 FromIterator
。
I don't think there is a 'safer' way to do this. The problem is that constant size arrays just don't get the same love as Vec
in Rust, as they can't implement FromIterator
.
这篇关于有没有一种办法不必两次初始化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!