How to I assign a value to a raw pointer at the module level in Rust?

292 Views Asked by At

If I have a raw pointer that is defined at the module level, how do I assign another value to it?

struct SomeStruct {
    field: u8,
}

// create a module level null raw pointer
static mut MODLEVELRAWPOINTER: *mut SomeStruct = std::ptr::null_mut::<SomeStruct>();

Because a static *mut SomeStruct cannot be in a let binding, the only way I can think of is to use std::mem::swap.

UPDATE / EDIT Thanks to @Sven for his answer!

struct SomeStruct {
    field: u8,
}

// create a module level null raw pointer
static mut MODLEVELRAWPOINTER: *mut SomeStruct = std::ptr::null_mut::<SomeStruct>();

fn main() {
    let mut x = SomeStruct { field: 42 };
    unsafe {
        MODLEVELRAWPOINTER = &mut x as *mut _;
    }
}
0

There are 0 best solutions below