std-type

Rust NonNull<T>

NonNull represents a pointer that cannot be null. The checked constructor rejects a null input; it does not establish that the address identifies initialized, accessible storage. NonNull does not own its target or track the target lifetime. Its covariance must be considered when designing mutable abstractions. Expected stdout (not executed): 8 Common mistake: Assuming NonNull automatically guarantees alignment, ownership or lifetime.

Formal Syntax & Structure

rust syntaxrust
NonNull::new(p: *mut T) -> Option<NonNull<T>>

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::ptr::{self, NonNull};    let mut value = 8_i32;    let p = NonNull::new(&mut value as *mut i32).unwrap();    assert!(NonNull::new(ptr::null_mut::<i32>()).is_none());    // SAFETY: pointer originates from a live exclusive borrow; only read here.    let result = unsafe { *p.as_ptr() };    println!("{result}");}
Rust Reference