std-method

Convert a nullable raw pointer into a shared reference

as_ref returns None for a null pointer and otherwise a shared reference whose lifetime must be justified by the caller. For the non-null branch, the full reference requirements must hold at creation; a null check cannot validate an arbitrary address. The example uses a reference-derived pointer, with no writes and a short local borrow. Expected stdout (not executed): 37 Common mistake: Returning the reference with an unconstrained lifetime that can outlive the storage.

Formal Syntax & Structure

rust syntaxrust
unsafe { p.as_ref() }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    let value = 37_i32;    let p: *const i32 = &value;    // SAFETY: p points to a live, initialized, aligned i32; no writes during the borrow.    let borrowed = unsafe { p.as_ref() }.unwrap();    println!("{borrowed}");}
Rust Reference