Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

pointers

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))
    }
}
like image 324
Florian Doyon Avatar asked May 26 '16 16:05

Florian Doyon


People also ask

How do you make a null pointer in Rust?

Working with raw pointers in Rust is uncommon, typically limited to a few patterns. Use the null and null_mut functions to create null pointers, and the is_null method of the *const T and *mut T types to check for null. The *const T and *mut T types also define the offset method, for pointer math.

How do you dereference a pointer in Rust?

To do this we need to dereference the memory address with the unary dereferencing operator (*). The dereference operator is also known as the indirection operator. Simply put, the dereferencing operator allows us to get the value stored in the memory address of a pointer.

Does Rust have raw pointers?

Rust only has two built-in pointer types now, references and raw pointers. Older Rusts had many more pointer types, they're gone now.

Can you set pointers to null?

We can directly assign the pointer variable to 0 to make it null pointer.


1 Answers

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))
}
like image 62
Shepmaster Avatar answered Nov 11 '22 10:11

Shepmaster