std::pin
最後更新
把值「釘」在記憶體中的固定位置,保證它在被釘住期間不會被移動。
這個模組做什麼
Rust 的值預設可以隨意移動(move):指派給新變數、傳進函式、放進
Vec 都可能讓它換到新的記憶體位址。大部分型別不在乎自己住在哪裡,但有一種型別很在乎:自我參照(self-referential) 的型別,也就是內部欄位指向自己另一個欄位的結構。一旦搬家,那個內部指標就會指向舊位址,變成懸垂指標。async fn 與 async 區塊編譯出來的 Future 正是這種型別:它在 .await 之間保存區域變數,而這些變數可能互相借用。所以 std::future 的 poll 要求 self: Pin<&mut Self>,先保證「之後不會再移動」,才能安全地推進狀態。| 名稱 | 用途 |
|---|---|
Pin<P> | 包住一個指標 P(如 &mut T、Box<T>),承諾被指向的值不再移動 |
Unpin | 標記特徵(trait):移動它也沒關係的型別,絕大多數型別自動實作 |
PhantomPinned | 放進結構裡讓整個型別「不是 Unpin」 |
pin! | 在堆疊上釘住一個值,得到 Pin<&mut T> |
Box::pin | 在堆積上釘住一個值,得到 Pin<Box<T>> |
比喻:
Pin 像是把一張便條紙用圖釘釘在白板上。你仍然可以讀它、在上面寫字(取得 &mut,只要型別允許),但不能把它拿下來貼到別處。匯入
- use std::pin::{Pin, pin};
- use std::marker::PhantomPinned;
Box::pin 是 Box 的關聯函式,Box 在 prelude 中(std::boxed::Box),不需要 use。Unpin 也在 prelude 中(完整路徑 std::marker::Unpin)。常用 API
Pin::new:釘住 Unpin 的值
對於實作
Unpin 的型別,釘住只是形式上的包裝,沒有額外限制,所以可以用安全的 Pin::new 直接建立。i32、String、Vec<T> 等一般型別都是 Unpin。Pin<P> 會透過 Deref 讓你讀取裡面的值。簽名:
- impl<Ptr: Deref<Target: Unpin>> Pin<Ptr> {
- pub const fn new(pointer: Ptr) -> Pin<Ptr>
- }
範例:
- use std::pin::Pin;
- fn main() {
- let mut name = String::from("ferris");
- let pinned: Pin<&mut String> = Pin::new(&mut name);
- println!("長度:{}", pinned.len());
- println!("內容:{}", *pinned);
- }
輸出:
- 長度:6
- 內容:ferris
Pin::get_mut 與 Pin::into_inner:取回內容
因為
Unpin 型別移動也安全,所以可以從 Pin<&mut T> 拿回普通的 &mut T,或用 Pin::into_inner 拆掉外殼取回原本的指標。注意:這兩個方法都要求
T: Unpin;對不是 Unpin 的型別呼叫會編譯失敗,這正是 Pin 保護你的方式。簽名:
- impl<'a, T: ?Sized> Pin<&'a mut T> {
- pub fn get_mut(self) -> &'a mut T where T: Unpin
- }
- impl<Ptr: Deref<Target: Unpin>> Pin<Ptr> {
- pub fn into_inner(pin: Pin<Ptr>) -> Ptr
- }
範例:
- use std::pin::Pin;
- fn main() {
- let mut scores = vec![60, 70];
- let pinned = Pin::new(&mut scores);
- let inner: &mut Vec<i32> = pinned.get_mut();
- inner.push(80);
- println!("{:?}", scores);
- let boxed = Pin::new(Box::new(5));
- let plain: Box<i32> = Pin::into_inner(boxed);
- println!("{}", *plain + 1);
- }
輸出:
- [60, 70, 80]
- 6
Box::pin:在堆積上釘住
Box::pin(x) 把值放到堆積(heap)上並立刻釘住。之後即使 Pin<Box<T>> 本身被移動,搬的只是指標,堆積上的值位置不變。這是最常見、也最簡單的釘住方式,任何型別(包括非 Unpin)都能用。它最常用在把不同的 Future 放進同一個集合:每個
async 區塊的型別都不同,裝箱成 Pin<Box<dyn Future>> 後就能統一處理。下面用 Waker::noop()(Rust 1.85 起)建立一個什麼都不做的喚醒器,手動呼叫 poll 一次。簽名:
- impl<T> Box<T> {
- pub fn pin(x: T) -> Pin<Box<T>>
- }
範例:
- use std::future::Future;
- use std::pin::Pin;
- use std::task::{Context, Poll, Waker};
- fn main() {
- let mut jobs: Vec<Pin<Box<dyn Future<Output = i32>>>> = vec![
- Box::pin(async { 1 + 1 }),
- Box::pin(async { 10 * 3 }),
- ];
- let mut cx = Context::from_waker(Waker::noop());
- for job in jobs.iter_mut() {
- match job.as_mut().poll(&mut cx) {
- Poll::Ready(v) => println!("完成:{v}"),
- Poll::Pending => println!("尚未完成"),
- }
- }
- }
輸出:
- 完成:2
- 完成:30
pin! 巨集:在堆疊上釘住
pin!(value)(Rust 1.68 起)把值移進目前的作用域並釘住,回傳 Pin<&mut T>,不需要配置堆積。適合「只在這個函式裡 poll 一個 Future」的情況,例如自己寫的 block_on。注意:
pin! 產生的 Pin<&mut T> 借用的是區域暫存值,不能回傳到函式外面。簽名:
- pub macro pin($value:expr $(,)?)
範例:
- use std::future::Future;
- use std::pin::pin;
- use std::task::{Context, Poll, Waker};
- async fn greet() -> &'static str {
- "哈囉"
- }
- fn main() {
- let mut fut = pin!(greet());
- let mut cx = Context::from_waker(Waker::noop());
- if let Poll::Ready(msg) = fut.as_mut().poll(&mut cx) {
- println!("{msg}");
- }
- }
輸出:
- 哈囉
Pin::as_mut:重複借用
poll 會消耗傳入的 Pin<&mut Self>。如果你手上是 Pin<Box<T>> 或想多次 poll 同一個值,就用 as_mut() 從 &mut Pin<P> 重新借出一個 Pin<&mut T>,原本的 Pin 仍可繼續使用。簽名:
- impl<Ptr: DerefMut> Pin<Ptr> {
- pub fn as_mut(&mut self) -> Pin<&mut Ptr::Target>
- }
範例:
- use std::future::Future;
- use std::pin::Pin;
- use std::task::{Context, Poll, Waker};
- struct Countdown(u32);
- impl Future for Countdown {
- type Output = &'static str;
- fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
- if self.0 == 0 {
- Poll::Ready("發射")
- } else {
- println!("剩下 {}", self.0);
- self.0 -= 1;
- Poll::Pending
- }
- }
- }
- fn main() {
- let mut fut = Box::pin(Countdown(3));
- let mut cx = Context::from_waker(Waker::noop());
- loop {
- if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
- println!("{v}");
- break;
- }
- }
- }
輸出:
- 剩下 3
- 剩下 2
- 剩下 1
- 發射
Pin::set:原地替換值
被釘住的值不能「搬出來」,但可以整個換成新值:
set 會先 drop 舊值,再把新值寫在同一個位置,因此不違反「不移動」的承諾,對非 Unpin 型別也能用。簽名:
- impl<Ptr: DerefMut<Target: Sized>> Pin<Ptr> {
- pub fn set(&mut self, value: Ptr::Target)
- }
範例:
- use std::pin::{Pin, pin};
- struct Tag(&'static str);
- impl Drop for Tag {
- fn drop(&mut self) {
- println!("丟棄 {}", self.0);
- }
- }
- fn main() {
- let mut slot: Pin<&mut Tag> = pin!(Tag("舊"));
- slot.set(Tag("新"));
- println!("目前是 {}", slot.0);
- }
輸出:
- 丟棄 舊
- 目前是 新
- 丟棄 新
Unpin 與 PhantomPinned:哪些型別真的被釘住
Unpin 是自動特徵(auto trait):只要所有欄位都是 Unpin,結構就自動是 Unpin。想讓自己的型別「必須被釘住才能用」,就放一個 PhantomPinned 欄位,它不佔空間,但會讓整個型別失去 Unpin。這時
Pin::new、get_mut 都不能用,只能用 Box::pin 或 pin! 釘住,並透過 get_ref(唯讀)或 as_ref 存取。async 區塊產生的 Future 一般也不是 Unpin。簽名:
- pub struct PhantomPinned;
- impl<'a, T: ?Sized> Pin<&'a T> {
- pub const fn get_ref(self) -> &'a T
- }
範例:
- use std::marker::PhantomPinned;
- use std::pin::Pin;
- struct Anchor {
- label: String,
- _pin: PhantomPinned,
- }
- fn needs_unpin<T: Unpin>(_: &T) -> &'static str {
- "是 Unpin"
- }
- fn main() {
- let a: Pin<Box<Anchor>> = Box::pin(Anchor {
- label: String::from("固定點"),
- _pin: PhantomPinned,
- });
- let r: &Anchor = a.as_ref().get_ref();
- println!("{}", r.label);
- println!("String {}", needs_unpin(&r.label));
- println!("Pin<Box<Anchor>> {}", needs_unpin(&a));
- }
輸出:
- 固定點
- String 是 Unpin
- Pin<Box<Anchor>> 是 Unpin
最後一行說明:
Anchor 本身不是 Unpin,但 Pin<Box<Anchor>> 這個「指標」是 Unpin,搬動指標不會移動堆積上的值。重點整理
Pin<P>承諾「被指向的值」不再移動,主要服務自我參照型別,尤其是 async 產生的 FutureUnpin型別被釘住也沒有限制,可用Pin::new、get_mut、Pin::into_inner自由進出- 非
Unpin型別用Box::pin(堆積)或pin!(堆疊)釘住;需要回傳或放進集合時選Box::pin - 多次 poll 同一個 Future 時用
as_mut()重新借出Pin<&mut T> - 加入
PhantomPinned欄位可讓自訂型別失去Unpin;相關標記特徵見 std::marker