Use Pin<T> to prevent a value from being moved after it has been pinned, which is required for self-referential types and async runtimes. Wrap the value in Pin::new or Pin::new_unchecked and access it via Pin::get or Pin::get_mut to ensure the memory address remains stable.
use std::pin::Pin;
struct SelfReferential {
data: String,
ptr: *const String,
}
fn main() {
let mut s = SelfReferential {
data: String::from("hello"),
ptr: std::ptr::null(),
};
let pin: Pin<&mut SelfReferential> = Pin::new(&mut s);
unsafe {
let ptr = Pin::get_unchecked_mut(pin);
ptr.ptr = &ptr.data as *const String;
}
}