Reputation: 4186
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
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