How to Use Pin and Unpin Correctly in Async Rust

Use `std::pin::pin!` to pin a value when you need to borrow it mutably across `.await` points in an async function. Pinning prevents the value from moving in memory, which is required for self-referential types or when using `Pin<&mut T>` in async runtimes.

How to Use Pin and Unpin Correctly in Async Rust

Use std::pin::pin! to pin a value when you need to borrow it mutably across .await points in an async function. Pinning prevents the value from moving in memory, which is required for self-referential types or when using Pin<&mut T> in async runtimes.

use std::pin::Pin;

fn main() {
    // Vec<T> is Unpin, so we don't need to pin it.
    // We can just use a mutable reference directly.
    let mut value = vec![1, 2, 3];
    
    // If we needed a Pin<&mut T> for some reason (e.g., passing to a function),
    // we would use Pin::new(&mut value).
    // However, for Unpin types, Pin::new is equivalent to a regular reference cast.
    let _pinned: Pin<&mut Vec<i32>> = Pin::new(&mut value);
    
    // Accessing the value
    let _ = value.as_mut();
}

To unpin, simply drop the Pin wrapper or move the value out of it if the type allows, but note that once pinned, you cannot move the value unless you explicitly unpin it using Pin::into_inner_unchecked (unsafe) or by ensuring the type implements Unpin.