expression

Build a borrowed slice only inside a verified pointer contract

Foreign buffers often arrive as pointer plus length. A non-null pointer alone is insufficient: memory must be aligned, initialized, readable, within one allocation and immutable for the borrow, and the total size must fit isize. Here the existing slice provides those guarantees. Handle an allowed null-plus-zero convention separately. Expected stdout (not executed): 24 Common mistake: Calling from_raw_parts with a null pointer even when len is zero.

Formal Syntax & Structure

rust syntaxrust
unsafe { std::slice::from_raw_parts(ptr, len) }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    let data = [4_u8, 8, 12];    let ptr = data.as_ptr();    let len = data.len();    // SAFETY: ptr and len come from the same live immutable array of initialized bytes.    let borrowed = unsafe { std::slice::from_raw_parts(ptr, len) };    println!("{}", borrowed.iter().map(|&v| u32::from(v)).sum::<u32>());}
Rust Reference