繁体   English   中英

如何在Rust中默认初始化包含数组的结构?

[英]How to default-initialize a struct containing an array in Rust?

声明包含数组的结构,然后创建零初始化实例的推荐方法是什么?

这是结构:

#[derive(Default)]
struct Histogram {
    sum: u32,
    bins: [u32; 256],
}

和编译器错误:

error[E0277]: the trait bound `[u32; 256]: std::default::Default` is not satisfied
 --> src/lib.rs:4:5
  |
4 |     bins: [u32; 256],
  |     ^^^^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `[u32; 256]`
  |
  = help: the following implementations were found:
            <[T; 14] as std::default::Default>
            <&'a [T] as std::default::Default>
            <[T; 22] as std::default::Default>
            <[T; 7] as std::default::Default>
          and 31 others
  = note: required by `std::default::Default::default`

如果我尝试为数组添加缺少的初始值设定项:

impl Default for [u32; 256] {
    fn default() -> [u32; 255] {
        [0; 256]
    }
}

我明白了:

error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
 --> src/lib.rs:7:5
  |
7 |     impl Default for [u32; 256] {
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl doesn't use types inside crate
  |
  = note: the impl does not reference any types defined in this crate
  = note: define and implement a trait or new type instead

难道我做错了什么?

Rust没有为所有数组实现Default ,因为它没有非类型多态。 因此, Default仅针对少数大小实现。

但是,您可以为您的类型实现默认值:

impl Default for Histogram {
    fn default() -> Histogram {
        Histogram {
            sum: 0,
            bins: [0; 256],
        }
    }
}

注意:我认为为u32实现Default是很可疑的; 为什么0而不是1 还是42 没有好的答案,所以没有明显的默认。

我担心你不能这样做,你需要自己为你的结构实现Default

struct Histogram {
    sum: u32,
    bins: [u32; 256],
}

impl Default for Histogram {
    #[inline]
    fn default() -> Histogram {
        Histogram {
            sum: 0,
            bins: [0; 256],
        }
    }
}

数字类型与此情况无关,更像是固定大小数组的问题。 他们仍然需要通用的数字文字来本地支持这种事情。

如果你确定用零初始化每个字段,这将起作用:

impl Default for Histogram {
    fn default() -> Histogram {
        unsafe { std::mem::zeroed() }
    }
}

实际上,在撰写本文时,标准库中仍然支持对固定长度数组的支持:

https://github.com/rust-lang/rust/issues/7622

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM