expression
Check a nullable foreign handle before use
Some foreign constructors report failure using a null pointer. NonNull::new converts this convention to Option. It only checks nullness: ownership, alignment, validity and lifetime must still be established by the foreign API. Expected stdout (not executed): true true Common mistake: Treating a non-null return value as proof of a valid object.
Formal Syntax & Structure
rust syntaxrust
NonNull::new(raw)Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { use std::ptr::{self, NonNull}; let missing = NonNull::<u32>::new(ptr::null_mut()); let mut value = 9_u32; let present = NonNull::new(&mut value as *mut u32); println!("{} {}", missing.is_none(), present.is_some());}