Pin<T> 固定指针 ​

什么是 Pin<T> ​

Rust 中的值默认是可以被移动的。当你把一个变量赋值给另一个变量、把值传入函数、或者 Vec 扩容重新分配内存时,值都会从一个内存地址搬到另一个内存地址。对于绝大部分类型来说这完全没问题,但有一类特殊的类型不能被移动——自引用类型(self-referential types)。

自引用类型是指结构体内部有一个指针指向自身的另一个字段。一旦结构体被移动到新的内存地址,这个内部指针就变成了悬垂指针,指向一块已经无效的内存。

Pin<P> 就是用来解决这个问题的。它包裹一个指针类型 P(比如 &mut T、Box<T>),保证指针指向的值不会被移动。这个保证是通过类型系统来实现的——Pin 不会让你拿到 &mut T(可变引用允许 mem::swap 等移动操作),除非 T 实现了 Unpin trait。

Pin 最重要的应用场景是异步编程。编译器为 async fn 生成的 Future 状态机可能包含自引用,因此 Future::poll 方法的签名是 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Output>——它要求 Future 在被轮询时必须是固定的。

为什么需要 Pin:自引用问题 ​

rust
// 这个例子展示了自引用类型的问题(概念演示,不要在实际代码中这样写)
struct SelfReferential {
    data: String,
    // 这个裸指针指向上面的 data 字段
    ptr: *const String,
}

impl SelfReferential {
    fn new(text: &str) -> Self {
        let mut s = SelfReferential {
            data: String::from(text),
            ptr: std::ptr::null(), // 先设为 null
        };
        // 让 ptr 指向 data
        s.ptr = &s.data as *const String;
        s
    }

    fn get_data_via_ptr(&self) -> &str {
        // 通过内部指针访问数据
        unsafe { &*self.ptr }
    }
}

fn main() {
    let a = SelfReferential::new("hello");
    println!("通过指针访问: {}", a.get_data_via_ptr()); // "hello",正常

    // 移动 a 到 b
    let b = a;
    // 此时 b.ptr 仍然指向 a 原来的内存地址
    // 但 a 的内存已经无效了!
    // println!("{}", b.get_data_via_ptr()); // 未定义行为!悬垂指针!
}

上面的代码就是 Pin 要解决的核心问题:一旦值被移动,内部的自引用指针就失效了。Pin 通过类型系统阻止你移动这样的值。

Unpin trait ​

Unpin 是一个自动 trait(auto trait),Rust 中绝大多数类型都自动实现了 Unpin。实现了 Unpin 的类型即使被 Pin 包裹,也可以自由移动——因为它们没有自引用,移动不会破坏任何东西。

rust
use std::pin::Pin;
use std::marker::Unpin;

fn main() {
    // 基本类型都实现了 Unpin
    let mut num = 42_i32;
    let pinned_num: Pin<&mut i32> = Pin::new(&mut num);
    // i32 是 Unpin 的,所以可以通过 get_mut 拿到 &mut i32
    let mutable_ref = pinned_num.get_mut();
    *mutable_ref = 100;
    println!("修改后: {}", num);

    // String, Vec, Box 等常见类型都是 Unpin 的
    let mut s = String::from("hello");
    let pinned_s = Pin::new(&mut s);
    // 可以自由获取可变引用
    pinned_s.get_mut().push_str(", world");

    // 只有包含 PhantomPinned 或 async 生成的 Future 等类型才是 !Unpin 的
}
类型是否 Unpin原因
i32, f64, bool 等基本类型是没有自引用
String, Vec, HashMap是内部指针指向堆,移动不影响
&T, &mut T是引用本身移动不影响被引用的值
Box<T>(当 T: Unpin)是移动 Box 只是移动指针
async fn 返回的 Future否可能包含自引用
包含 PhantomPinned 的类型否显式标记为不可移动

Pin 的创建方式 ​

堆上固定:Box::pin ​

rust
use std::pin::Pin;

async fn compute() -> i32 {
    42
}

fn main() {
    // Box::pin 把值放到堆上并固定
    // 返回 Pin<Box<T>>
    let pinned_future: Pin<Box<dyn std::future::Future<Output = i32>>> =
        Box::pin(compute());

    // 对于 Unpin 类型,Box::pin 也能用,但没有必要
    let pinned_num: Pin<Box<i32>> = Box::pin(42);
    println!("pinned_num: {}", pinned_num);
}

栈上固定:pin! 宏 ​

rust
use std::pin::pin;

async fn do_something() -> String {
    String::from("done")
}

// pin! 宏把值固定在栈上,返回 Pin<&mut T>
// 注意:pin! 宏在 Rust 1.68 稳定
async fn example() {
    let future = do_something();
    // pin! 宏在栈上固定 future
    let pinned = pin!(future);
    // pinned 的类型是 Pin<&mut impl Future<Output = String>>
    // 现在可以安全地 poll 这个 future 了
    let _ = pinned;
}

对 Unpin 类型使用 Pin::new ​

rust
use std::pin::Pin;

fn main() {
    // Pin::new 只能用于 Unpin 类型
    let mut value = 42_i32;
    let pinned = Pin::new(&mut value);
    println!("pinned value: {}", *pinned);

    // 对于 !Unpin 类型,不能用 Pin::new
    // 需要用 Box::pin 或 pin! 宏
}

Pin 在异步编程中的作用 ​

这是 Pin 最核心的应用场景。Future::poll 方法要求 self 是 Pin<&mut Self>,因为 async 生成的 Future 可能包含自引用。

rust
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

// 手动实现一个简单的 Future
struct CountdownFuture {
    count: u32,
}

impl Future for CountdownFuture {
    type Output = String;

    // poll 方法的第一个参数是 Pin<&mut Self>
    // 这保证了 Future 在被轮询期间不会被移动
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.count == 0 {
            // Future 完成
            Poll::Ready(String::from("倒计时结束"))
        } else {
            // 还没完成,修改内部状态
            self.count -= 1;
            // 通知运行时稍后再来轮询
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

// 因为 CountdownFuture 没有自引用,它自动实现 Unpin
// 所以这里的 Pin 实际上不限制任何东西
// 但 Future trait 要求 poll 的签名必须是 Pin<&mut Self>

fn main() {
    // 创建 Future 并固定
    let future = CountdownFuture { count: 3 };
    let pinned = Box::pin(future);
    // pinned 会被传递给异步运行时来驱动执行
    println!("Future 已创建并固定");
}

PhantomPinned:手动标记为不可移动 ​

如果你要创建一个不应该被移动的类型,可以在结构体中加入 PhantomPinned 字段,这会让类型不再自动实现 Unpin。

rust
use std::marker::PhantomPinned;
use std::pin::Pin;

// 一个地址敏感的类型
struct AddrTracker {
    // 记录自己被创建时的地址
    address: usize,
    // PhantomPinned 让这个类型变成 !Unpin
    _marker: PhantomPinned,
}

impl AddrTracker {
    fn new() -> Self {
        let tracker = AddrTracker {
            address: 0,
            _marker: PhantomPinned,
        };
        tracker
    }

    // 初始化:记录当前地址(需要在 pin 之后调用)
    fn init(self: Pin<&mut Self>) {
        let self_addr = &*self as *const Self as usize;
        // 通过 unsafe 修改 pin 内部的值
        // 这是安全的,因为我们没有移动值,只是修改了一个字段
        unsafe {
            let this = self.get_unchecked_mut();
            this.address = self_addr;
        }
    }

    // 验证地址是否改变
    fn verify(self: Pin<&Self>) {
        let current_addr = &*self as *const Self as usize;
        if self.address == current_addr {
            println!("地址验证通过: 值没有被移动 (地址: 0x{:x})", current_addr);
        } else {
            println!("地址验证失败: 值被移动了!");
        }
    }
}

fn main() {
    // 在堆上固定
    let mut tracker = Box::pin(AddrTracker::new());

    // 初始化:记录当前地址
    tracker.as_mut().init();

    // 验证地址
    tracker.as_ref().verify(); // 通过

    // 因为 AddrTracker 是 !Unpin 的,下面的代码编译不通过:
    // let moved = *tracker; // 错误:不能移动 Pin 内的 !Unpin 值
    // std::mem::swap(&mut *tracker, &mut other); // 错误
}

pin-project 模式 ​

在实际项目中,如果你有一个结构体只有部分字段需要 pin,可以用"投影"(projection)的方式来分别处理 pinned 和 unpinned 的字段。pin-project crate 提供了方便的宏来实现这一点。

rust
// 手动实现投影的概念(实际项目中建议用 pin-project crate)
use std::pin::Pin;
use std::future::Future;
use std::task::{Context, Poll};

struct TimedFuture<F: Future> {
    // 这个字段需要被 pin(因为 F 可能是 !Unpin 的 Future)
    inner: F,
    // 这个字段不需要被 pin(bool 是 Unpin 的)
    started: bool,
}

impl<F: Future> TimedFuture<F> {
    fn new(future: F) -> Self {
        TimedFuture {
            inner: future,
            started: false,
        }
    }
}

impl<F: Future> Future for TimedFuture<F> {
    type Output = F::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // 通过 unsafe 进行投影:分别获取 pinned 和 unpinned 字段
        let (inner, started) = unsafe {
            let this = self.get_unchecked_mut();
            (
                // inner 字段需要保持 pinned
                Pin::new_unchecked(&mut this.inner),
                // started 字段可以自由访问
                &mut this.started,
            )
        };

        if !*started {
            *started = true;
            println!("Future 开始执行");
        }

        // 轮询内部的 Future
        match inner.poll(cx) {
            Poll::Ready(output) => {
                println!("Future 执行完毕");
                Poll::Ready(output)
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

基本示例 ​

一个综合示例,展示 Pin 在异步 select 场景中的使用:

rust
use std::pin::pin;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

// 一个简单的延迟 Future
struct Delay {
    // 剩余轮询次数
    remaining: u32,
    // 完成时返回的消息
    message: String,
}

impl Delay {
    fn new(polls: u32, message: &str) -> Self {
        Delay {
            remaining: polls,
            message: String::from(message),
        }
    }
}

impl Future for Delay {
    type Output = String;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.remaining == 0 {
            // 返回消息的克隆,因为 Pin 不允许直接移出
            Poll::Ready(self.message.clone())
        } else {
            // 减少剩余次数
            self.remaining -= 1;
            // 请求再次轮询
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

// 模拟一个接受 Pin<&mut dyn Future> 的函数
fn poll_once(
    future: Pin<&mut (dyn Future<Output = String>)>,
    cx: &mut Context<'_>,
) -> Poll<String> {
    future.poll(cx)
}

fn main() {
    println!("Pin 的基本使用:");

    // 堆上固定
    let boxed_delay: Pin<Box<dyn Future<Output = String>>> =
        Box::pin(Delay::new(3, "堆上的延迟"));
    println!("  创建了堆上固定的 Future");

    // 栈上固定(在 async 上下文中更常用)
    // let pinned = pin!(Delay::new(2, "栈上的延迟"));

    // 对 Unpin 类型的 Pin 是透明的
    let mut num = 42;
    let pinned_num = Pin::new(&mut num);
    // 因为 i32 是 Unpin 的,可以直接获取 &mut
    let mutable = pinned_num.get_mut();
    *mutable = 100;
    println!("  Unpin 类型可以自由修改: {}", num);

    println!("  Pin 主要在异步运行时内部使用");
    println!("  大多数情况下你不需要直接操作 Pin");
}

常见问题 ​

问题一:我在写普通代码时需要关心 Pin 吗?

大多数情况下不需要。Pin 主要在以下场景才会遇到:(1)手动实现 Future trait;(2)使用底层异步 API;(3)创建自引用数据结构;(4)编写异步运行时或库。如果你只是用 async/await 语法写异步代码,编译器和运行时会帮你处理好 Pin 相关的一切。

问题二:为什么 Future::poll 需要 Pin<&mut Self>?

因为 async 块编译后生成的状态机可能包含自引用。比如一个 async 块中先创建了一个局部变量,然后在 .await 之后又引用了这个变量——在状态机中,这个引用和变量都存储在同一个结构体里,形成了自引用。如果这个结构体被移动,引用就会失效。Pin 保证了状态机在被轮询期间不会被移动。

问题三:Pin<Box<T>> 和 Box<T> 有什么区别?

特性Box<T>Pin<Box<T>>
可以解引用移出值是(*boxed)不可以(如果 T: !Unpin)
可以获取 &mut T是只有 T: Unpin 时可以
可以 mem::swap是不可以(如果 T: !Unpin)
数据在堆上是是
内存开销一个指针一个指针(Pin 是零开销包装)

问题四:Pin 有运行时开销吗?

没有。Pin 是一个零开销抽象(zero-cost abstraction),它只在编译期通过类型系统提供保证,运行时的内存布局和性能和不用 Pin 完全一样。Pin<Box<T>> 和 Box<T> 在内存中的表示完全相同。

适用场景 ​

  • 异步编程:Future::poll 方法要求 Pin<&mut Self>,这是 Pin 最常见的使用场景
  • 自引用数据结构:结构体内部有指针指向自身的其他字段时,需要用 Pin 保证不被移动
  • 侵入式链表:节点包含指向其他节点的指针,节点的地址不能改变
  • C FFI 回调:C 库可能保存了指向 Rust 值的指针,这个值不能被移动
  • 自定义 Future 实现:手动实现 Future trait 时需要处理 Pin
  • 流处理(Stream):Stream::poll_next 同样需要 Pin<&mut Self>

注意事项 ​

  • 大多数 Rust 类型自动实现 Unpin,对这些类型来说 Pin 是透明的,不会限制任何操作
  • 要让类型变成 !Unpin,在结构体中加入 PhantomPinned 字段
  • Pin::new 只能用于 Unpin 类型,对 !Unpin 类型需要用 Box::pin 或 pin! 宏
  • Pin::get_unchecked_mut 是 unsafe 的,使用时必须保证不会移动数据
  • 不要试图通过 mem::swap、mem::replace 等方式移动被 pin 的 !Unpin 值
  • pin! 宏(std::pin::pin)在 Rust 1.68 稳定,栈上固定值时优先使用它
  • 在实际项目中处理结构体的 pin 投影时,建议使用 pin-project 或 pin-project-lite crate,避免手写 unsafe 代码
  • Pin<&mut T> 固定的是 T,不是指针本身。指针本身(&mut T)仍然可以被移动,被固定的是指针指向的那个值

总结 ​

Pin<P> 通过类型系统保证指针指向的值不会被移动,解决了自引用类型在移动后内部指针失效的问题。Rust 中绝大多数类型都实现了 Unpin trait,对它们来说 Pin 完全透明,没有任何限制。Pin 真正发挥作用的场景是异步编程——async 块编译生成的 Future 状态机可能包含自引用,Future::poll 要求 Pin<&mut Self> 就是为了保证这些自引用在轮询期间不会失效。在日常编写 async/await 代码时,你几乎不需要直接操作 Pin,编译器和异步运行时会帮你处理好一切。只有在手动实现 Future、编写异步运行时、或创建自引用数据结构时,才需要理解和使用 Pin。Pin 是零开销的——它只在编译期提供保证,不会增加任何运行时开销。