Pinned Memory for Async State Machines
The 'Pin' wrapper ensures that a value stays at a fixed memory address. This is critical for self-referential structs where a field stores a pointer to another field within the same object. If the object moved, the internal pointer would become dangling.
use std::pin::Pin;use std::marker::PhantomPinned;struct SelfReferential {data: String,ptr: *const String,_pin: PhantomPinned,}impl SelfReferential {pub fn new(data: String) -> Pin<Box<Self>> {let res = SelfReferential {data,ptr: std::ptr::null(),_pin: PhantomPinned,};let mut boxed = Box::pin(res);let self_ptr: *const String = &boxed.data;unsafe {let mut_ref: Pin<&mut Self> = boxed.as_mut();Pin::get_unchecked_mut(mut_ref).ptr = self_ptr;}boxed}}