std-method

Change the pointee type with cast

Casting a thin raw pointer to another sized pointee type changes its type, not the underlying bytes. It does not initialize memory or grant access to more storage. Reading an arbitrary byte of an initialized byte array is well-defined here; no representation assumptions about multi-byte values are needed. Expected stdout (not executed): 65 Common mistake: Casting a pointer to a larger type and reading without proving size, alignment and validity.

Formal Syntax & Structure

rust syntaxrust
p.cast::<U>()

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    let bytes = [65_u8, 66];    let array_ptr = &raw const bytes;    let first = array_ptr.cast::<u8>();    // SAFETY: first points at the first initialized byte of the live array.    println!("{}", unsafe { *first });}
Rust Reference