std-function

Initialize through an out-pointer

A function can initialize caller-provided storage through a raw pointer. A safe wrapper that takes &mut MaybeUninit<T> can establish the storage contract. Raw pointer write transfers ownership without reading or destroying previous contents. Avoid overwriting a live resource without cleaning it up. Expected stdout (not executed): ready Common mistake: Creating a &mut String reference before a valid String exists.

Formal Syntax & Structure

rust syntaxrust
slot.as_mut_ptr(); unsafe { ptr::write(dst, value) }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::{mem::MaybeUninit, ptr};    fn fill(slot: &mut MaybeUninit<String>) {        let dst = slot.as_mut_ptr();        // SAFETY: dst is valid aligned writable storage from the exclusive borrow.        unsafe { ptr::write(dst, String::from("ready")); }    }    let mut slot = MaybeUninit::uninit();    fill(&mut slot);    // SAFETY: fill returned normally after writing a complete String.    let text = unsafe { slot.assume_init() };    println!("{text}");}
Rust Reference