什么是初始化一个固定长度的数组的正确方法? [英] What is the proper way to initialize a fixed length array?
问题描述
我无法初始化一个固定长度的数组。我尝试到目前为止,所有的结果在同一个使用可能未初始化的变量的: foo_array
。误差
I'm having trouble initializing a fixed length array. 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);
}
}
我实现了默认
特质,但似乎锈默认情况下并不类似于C ++的构造函数。
I implemented the Default
trait, but Rust does not seem to call this by default akin to a C++ constructor.
什么是初始化一个固定长度的数组的正确方法?我想要做一个有效的就地初始化,而不是某种形式的副本。
What is the proper way to initialize a fixed length array? I'd like to do an efficient in-place initialization rather than some sort of copy.
相关报道:<一href=\"http://stackoverflow.com/questions/27876588/why-is-the-copy-trait-needed-for-default-struct-valued-array-initialization\">Why需要对默认(结构价值)数组初始化复制特质?
相关报道:<一href=\"http://stackoverflow.com/questions/26185618/is-there-a-way-to-not-have-to-initialize-arrays-twice\">Is有没有办法不用两次初始化数组?
推荐答案
在安全的,但有点低效的解决方案:
The safe but somewhat inefficient solution:
#[derive(Copy, Clone, Debug)]
struct Foo { a: u32, b: u32 }
fn main() {
let mut foo_array = [Foo { a: 10, b: 10 }; 10];
}
既然你是专门要求一个解决方案,无需拷贝:
Since you're specifically asking for a solution without copies:
use std::mem;
use std::ptr;
#[derive(Debug)]
struct Foo { a: u32, b: u32 }
// We're just implementing Drop to prove there are no unnecessary copies.
impl Drop for Foo {
fn drop(&mut self) {
println!("Destructor running for a Foo");
}
}
pub fn main() {
let array = unsafe {
// Create an uninitialized array.
let mut array: [Foo; 10] = mem::uninitialized();
for (i, element) in array.iter_mut().enumerate() {
let foo = Foo { a: i as u32, b: 0 };
// Overwrite `element` without running the destructor of the old value.
// Since Foo does not implement Copy, it is moved.
ptr::write(element, foo)
}
array
};
for element in array.iter() {
println!("{:?}", element);
}
}
这篇关于什么是初始化一个固定长度的数组的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!