Remix.run Logo
▲ ninkendo 6 hours ago

Yep, that's std::mem::zeroed(), which just writes zeroes into the allocated memory regardless of its type... also only available in unsafe code.

    #[derive(Debug)]
    struct Foo {
        _i: i32,
    }

    fn main() {
        let x: i32 = unsafe { std::mem::zeroed() };
        println!("x={x}");
        let f: Foo = unsafe { std::mem::zeroed() };
        println!("f={f:?}");
    }
prints:

    x=0
    f=Foo { _i: 0 }
It's unsafe because if Foo contained a String, it would be string with a null pointer inside it and you'd crash trying to read it. If you want "Default" values instead of zeroed (ie. you don't want to run unsafe code), that's what the Default trait is for, and this becomes:

    #[derive(Debug, Default)]
    struct Foo {
        _i: i32,
    }

    fn main() {
        let x: i32 = Default::default();
        println!("x={x}");
        let f: Foo = Default::default();
        println!("f={f:?}");
    }
and prints the same thing.