Pin Heap Values With Box::pin

Pin values to the heap with Box::pin: Unpin types keep mutable access, while !Unpin futures expose only shared references and set swaps the box.

RustData Integrity

Code

rustsnippet
21 lines
use std::future::{Future, Ready};
use std::pin::Pin;

fn main() {
    // Box::pin 把值钉进堆:安全 API 拿不到能把值移出去的出口
    let mut counter: Pin<Box<u32>> = Box::pin(41);

    // u32 实现 Unpin:Pin 依旧提供 as_mut / DerefMut,普通更新不受影响
    *counter.as_mut() += 1;
    println!("counter: {counter}");

    // dyn Future 默认 !Unpin:只能 as_ref().get_ref() 拿共享引用,
    // get_mut 在这里无法编译——这正是 Pin 要保证的事
    let job: Pin<Box<dyn Future<Output = u32>>> = Box::pin(Ready::new(7));
    let _shared: &dyn Future<Output = u32> = job.as_ref().get_ref();

    // set 换掉整个装箱内容:目标类型 Sized 即可,不需要 Unpin
    let mut sized_job: Pin<Box<Ready<u32>>> = Box::pin(Ready::new(1));
    sized_job.set(Ready::new(9));
    println!("sized job replaced ok");
}

The logic in sequence

The working surface is the function main — everything else is wiring.

Points of care

  • You can run it without adding anything to the project first.

Putting it to use

Read from this declaration: fn main()

Output lines are prefixed (counter:, sized job replaced ok), and each line keeps pointing at the step it came from.

Core lines

let job: Pin<Box<dyn Future<Output = u32>>> = Box::pin(Ready::new(7));
let mut sized_job: Pin<Box<Ready<u32>>> = Box::pin(Ready::new(1));
let _shared: &dyn Future<Output = u32> = job.as_ref().get_ref();

Interactive Tools for This Topic

FAQ

What does Pin Heap Values With Box::pin print when run?
Invoke the file as-is — the `counter:`, `sized job replaced ok` prefixes identify which step printed each line.