【发布时间】:2020-04-17 10:45:09
【问题描述】:
我在初始化固定长度数组时遇到问题。 My attempts so far all result in the same "use of possibly uninitialized variable: foo_array" error:
#[derive(Debug)]
struct Foo { a: u32, b: u32 }
impl Default for Foo {
fn default() -> Foo { Foo{a:1, b:2} }
}
pub fn main() {
let mut foo_array: [Foo; 10];
// Do something here to in-place initialize foo_array?
for f in foo_array.iter() {
println!("{:?}", f);
}
}
error[E0381]: use of possibly uninitialized variable: `foo_array`
--> src/main.rs:13:14
|
13 | for f in foo_array.iter() {
| ^^^^^^^^^ use of possibly uninitialized `foo_array`
我实现了Default trait,但默认情况下,Rust 似乎不像 C++ 构造函数那样调用它。
初始化固定长度数组的正确方法是什么?我想做一个有效的就地初始化而不是某种复制。
相关:Why is the Copy trait needed for default (struct valued) array initialization?
【问题讨论】:
-
Rust 似乎没有默认调用它——这是正确的。编译器不会以任何特殊方式使用
Default特征。它仅供程序员使用。