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))
}
}
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.
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.
Rust only has two built-in pointer types now, references and raw pointers. Older Rusts had many more pointer types, they're gone now.
We can directly assign the pointer variable to 0 to make it null pointer.
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With