← 中文资源

简体中文版本

用 Box::pin 把值钉在堆上

Box::pin 提供 Pin<Box<T>>:Unpin 类型照常可变访问,dyn Future 这类 !Unpin 只给共享引用,set 可以整体替换装箱内容。

阅读英文原文

实现说明

用 Box::pin 把值钉在堆上以函数 main为骨架。

使用要点

  • 演示输出是带标签的(counter:、sized job replaced ok),每个操作都会留下自己的一行标注。

常见问题

运行「用 Box::pin 把值钉在堆上」会打印什么?

运行文件本身,counter:、sized job replaced ok 这些前缀各对应一段演示逻辑。

核心语句

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();

代码示例

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");
}