arrays - 初始化固定长度数组的正确方法是什么?

标签 arrays rust

我在初始化固定长度数组时遇到问题。 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?

相关:Is there a way to not have to initialize arrays twice?

最佳答案

安全但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];
}

由于您特别要求 a solution without copies :

use std::mem::MaybeUninit;

#[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 = {
        // Create an array of uninitialized values.
        let mut array: [MaybeUninit<Foo>; 10] = unsafe { MaybeUninit::uninit().assume_init() };

        for (i, element) in array.iter_mut().enumerate() {
            let foo = Foo { a: i as u32, b: 0 };
            *element = MaybeUninit::new(foo);
        }

        unsafe { std::mem::transmute::<_, [Foo; 10]>(array) }
    };

    for element in array.iter() {
        println!("{:?}", element);
    }
}

这是由 the documentation of MaybeUninit 推荐的.

关于arrays - 初始化固定长度数组的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67320434/

相关文章:

rust - 未找到方法/字段名称

rust - 如何以方便的方式对齐堆上的内存(在一个盒子里)?

javascript - 使用map循环遍历数组时返回null而不是JSX

javascript - lodash:根据日期聚合和减少对象数组

javascript - 如何删除包含相同 `place` 的重复 `name` 名称?

C++回文检查解决方案被一个测试用例触发

c - 传递数组作为参数 C

rust - 为新类型实现 Deref 是否被认为是一种不好的做法?

Rust:在结构中保存过滤器

testing - 如何只运行库和集成测试?