Florian Doyon
Florian Doyon

Reputation: 4186

Is it possible to match against a NULL pointer in Rust?

Calling is_null() feels a bit odd:

fn do_stuff(ptr: *const i32) -> Option<i32> {
    if ptr.is_null() {
        None
    } else {
        Some(do_transform(*ptr, 42))
    }
}

Upvotes: 12

Views: 8088

Answers (1)

Shepmaster
Shepmaster

Reputation: 431529

As of Rust 1.9, there's a function as_ref that converts a raw pointer to an Option<&T>, and a mutable variant as_mut:

Your code would look something like

fn do_stuff(ptr: *const i32) -> Option<i32> {
    let ptr = unsafe { ptr.as_ref() };
    ptr.map(|x| do_transform(x, 42))
}

Upvotes: 25

Related Questions