Initialize a large, fixed-size array with non-Copy types

后端 未结 3 479
醉梦人生
醉梦人生 2020-11-27 08:22

I’m trying to initialize a fixed-size array of some nullable, non-copyable type, like an Option> for some kind of Thing. I’d

3条回答
  •  悲&欢浪女
    2020-11-27 08:32

    I'm copying the answer by chris-morgan and adapting it to match the question better, to follow the recommendation by dbaupp downthread, and to match recent syntax changes:

    use std::mem;
    use std::ptr;
    
    #[derive(Debug)]
    struct Thing {
        number: usize,
    }
    
    macro_rules! make_array {
        ($n:expr, $constructor:expr) => {{
            let mut items: [_; $n] = mem::uninitialized();
            for (i, place) in items.iter_mut().enumerate() {
                ptr::write(place, $constructor(i));
            }
            items
        }}
    }
    
    const SIZE: usize = 50;
    
    fn main() {
        let items = unsafe { make_array!(SIZE, |i| Box::new(Some(Thing { number: i }))) };
        println!("{:?}", &items[..]);
    }
    

    Note the need to use unsafe here: The problem is that if the constructor function panic!s, this would lead to undefined behavior.

提交回复
热议问题