How to initialize a structure containing an array in Rust?

What is the recommended way to declare a structure containing an array and then create a zero initialized instance?

Here is the structure:

use std::default::Default; use std::num; #[deriving(Default)] struct Histogram { sum: u32, bins: [u32, ..256], } 

and compiler error:

 src/lib.rs:17:5: 17:23 error: the trait `core::default::Default` is not implemented for the type `[u32, ..256]` src/lib.rs:17 bins: [u32, ..256], ^~~~~~~~~~~~~~~~~~ note: in expansion of #[deriving] src/lib.rs:14:1: 14:21 note: expansion site src/lib.rs:17:5: 17:23 note: the trait `core::default::Default` must be implemented because it is required by `core::default::Default::default` src/lib.rs:17 bins: [u32, ..256], ^~~~~~~~~~~~~~~~~~ note: in expansion of #[deriving] src/lib.rs:14:1: 14:21 note: expansion site error: aborting due to previous error 

If I try to add a missing initializer for the uint8 array:

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

I get:

 src/lib.rs:20:1: 24:2 error: cannot provide an extension implementation where both trait and type are not defined in this crate [E0117] src/lib.rs:20 impl Default for [u32,..256] { src/lib.rs:21 fn default () -> [u32,..255]{ src/lib.rs:22 [0u8,..256] src/lib.rs:23 } src/lib.rs:24 } 

Am I doing something wrong or will I be bitten by a beating in the standard library for numeric types on the road to 1.0?

 $ rustc --version rustc 0.13.0-nightly 
+6
source share
4 answers

Rust does not implement Default for all arrays, because it does not have non-piggy polymorphism, since Default is implemented only for several sizes.

However, you can implement the default for your type:

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

Note. I would argue that the Default implementation for u32 is logical to start with, why 0 and not 1 ? or 42 ? There is no good answer, so there is really no obvious default.

+3
source

I am afraid that you cannot do this, you need to implement Default for your structure:

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

Numeric types have nothing to do with this case; it is more like problems with fixed-size arrays. They still need generic numeric literals to support this kind of thing.

+3
source

If you necessarily initialize each field to zero, this will work:

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

Indeed, at the time of writing, support for fixed-length arrays is still stored in the standard library:

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

+1
source

Source: https://habr.com/ru/post/978518/


All Articles