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

前端 未结 4 587
难免孤独
难免孤独 2021-01-11 10:31

What is the recommended way to declare a struct that contains an array, and then create a zero-initialized instance?

Here is the struct:

#[derive(De         


        
相关标签:
4条回答
  • 2021-01-11 11:25

    If you're sure to initialize every field with zero, this would work:

    impl Default for Histogram {
        fn default() -> Histogram {
            unsafe { std::mem::zeroed() }
        }
    }
    
    0 讨论(0)
  • 2021-01-11 11:29

    Rust does not implement Default for all arrays because it does not have non-type polymorphism. As such, Default is only implemented for a handful of sizes.

    You can, however, implement a default for your type:

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

    Note: I would contend that implementing Default for u32 is fishy to start with; why 0 and not 1? or 42? There is no good answer, so no obvious default really.

    0 讨论(0)
  • 2021-01-11 11:30

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

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

    0 讨论(0)
  • 2021-01-11 11:32

    I'm afraid you can't do this, you will need to implement Default for your structure yourself:

    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's more like problems with fixed-size arrays. They still need generic numerical literals to support this kind of things natively.

    0 讨论(0)
提交回复
热议问题