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,只要型別允許),但不能把它拿下來貼到別處。

匯入


  1. use std::pin::{Pin, pin};
  2. 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 讓你讀取裡面的值。
簽名:
  1. impl<Ptr: Deref<Target: Unpin>> Pin<Ptr> {
  2. pub const fn new(pointer: Ptr) -> Pin<Ptr>
  3. }

範例:
  1. use std::pin::Pin;
  2. fn main() {
  3. let mut name = String::from("ferris");
  4. let pinned: Pin<&mut String> = Pin::new(&mut name);
  5. println!("長度:{}", pinned.len());
  6. println!("內容:{}", *pinned);
  7. }

輸出:
  1. 長度:6
  2. 內容:ferris

Pin::get_mut 與 Pin::into_inner:取回內容


因為 Unpin 型別移動也安全,所以可以從 Pin<&mut T> 拿回普通的 &mut T,或用 Pin::into_inner 拆掉外殼取回原本的指標。
注意:這兩個方法都要求 T: Unpin;對不是 Unpin 的型別呼叫會編譯失敗,這正是 Pin 保護你的方式。
簽名:
  1. impl<'a, T: ?Sized> Pin<&'a mut T> {
  2. pub fn get_mut(self) -> &'a mut T where T: Unpin
  3. }
  4. impl<Ptr: Deref<Target: Unpin>> Pin<Ptr> {
  5. pub fn into_inner(pin: Pin<Ptr>) -> Ptr
  6. }

範例:
  1. use std::pin::Pin;
  2. fn main() {
  3. let mut scores = vec![60, 70];
  4. let pinned = Pin::new(&mut scores);
  5. let inner: &mut Vec<i32> = pinned.get_mut();
  6. inner.push(80);
  7. println!("{:?}", scores);
  8. let boxed = Pin::new(Box::new(5));
  9. let plain: Box<i32> = Pin::into_inner(boxed);
  10. println!("{}", *plain + 1);
  11. }

輸出:
  1. [60, 70, 80]
  2. 6

Box::pin:在堆積上釘住


Box::pin(x) 把值放到堆積(heap)上並立刻釘住。之後即使 Pin<Box<T>> 本身被移動,搬的只是指標,堆積上的值位置不變。這是最常見、也最簡單的釘住方式,任何型別(包括非 Unpin)都能用。
它最常用在把不同的 Future 放進同一個集合:每個 async 區塊的型別都不同,裝箱成 Pin<Box<dyn Future>> 後就能統一處理。下面用 Waker::noop()(Rust 1.85 起)建立一個什麼都不做的喚醒器,手動呼叫 poll 一次。
簽名:
  1. impl<T> Box<T> {
  2. pub fn pin(x: T) -> Pin<Box<T>>
  3. }

範例:
  1. use std::future::Future;
  2. use std::pin::Pin;
  3. use std::task::{Context, Poll, Waker};
  4. fn main() {
  5. let mut jobs: Vec<Pin<Box<dyn Future<Output = i32>>>> = vec![
  6. Box::pin(async { 1 + 1 }),
  7. Box::pin(async { 10 * 3 }),
  8. ];
  9. let mut cx = Context::from_waker(Waker::noop());
  10. for job in jobs.iter_mut() {
  11. match job.as_mut().poll(&mut cx) {
  12. Poll::Ready(v) => println!("完成:{v}"),
  13. Poll::Pending => println!("尚未完成"),
  14. }
  15. }
  16. }

輸出:
  1. 完成:2
  2. 完成:30

pin! 巨集:在堆疊上釘住


pin!(value)(Rust 1.68 起)把值移進目前的作用域並釘住,回傳 Pin<&mut T>,不需要配置堆積。適合「只在這個函式裡 poll 一個 Future」的情況,例如自己寫的 block_on。
注意:pin! 產生的 Pin<&mut T> 借用的是區域暫存值,不能回傳到函式外面。
簽名:
  1. pub macro pin($value:expr $(,)?)

範例:
  1. use std::future::Future;
  2. use std::pin::pin;
  3. use std::task::{Context, Poll, Waker};
  4. async fn greet() -> &'static str {
  5. "哈囉"
  6. }
  7. fn main() {
  8. let mut fut = pin!(greet());
  9. let mut cx = Context::from_waker(Waker::noop());
  10. if let Poll::Ready(msg) = fut.as_mut().poll(&mut cx) {
  11. println!("{msg}");
  12. }
  13. }

輸出:
  1. 哈囉

Pin::as_mut:重複借用


poll 會消耗傳入的 Pin<&mut Self>。如果你手上是 Pin<Box<T>> 或想多次 poll 同一個值,就用 as_mut() 從 &mut Pin<P> 重新借出一個 Pin<&mut T>,原本的 Pin 仍可繼續使用。
簽名:
  1. impl<Ptr: DerefMut> Pin<Ptr> {
  2. pub fn as_mut(&mut self) -> Pin<&mut Ptr::Target>
  3. }

範例:
  1. use std::future::Future;
  2. use std::pin::Pin;
  3. use std::task::{Context, Poll, Waker};
  4. struct Countdown(u32);
  5. impl Future for Countdown {
  6. type Output = &'static str;
  7. fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
  8. if self.0 == 0 {
  9. Poll::Ready("發射")
  10. } else {
  11. println!("剩下 {}", self.0);
  12. self.0 -= 1;
  13. Poll::Pending
  14. }
  15. }
  16. }
  17. fn main() {
  18. let mut fut = Box::pin(Countdown(3));
  19. let mut cx = Context::from_waker(Waker::noop());
  20. loop {
  21. if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
  22. println!("{v}");
  23. break;
  24. }
  25. }
  26. }

輸出:
  1. 剩下 3
  2. 剩下 2
  3. 剩下 1
  4. 發射

Pin::set:原地替換值


被釘住的值不能「搬出來」,但可以整個換成新值:set 會先 drop 舊值,再把新值寫在同一個位置,因此不違反「不移動」的承諾,對非 Unpin 型別也能用。
簽名:
  1. impl<Ptr: DerefMut<Target: Sized>> Pin<Ptr> {
  2. pub fn set(&mut self, value: Ptr::Target)
  3. }

範例:
  1. use std::pin::{Pin, pin};
  2. struct Tag(&'static str);
  3. impl Drop for Tag {
  4. fn drop(&mut self) {
  5. println!("丟棄 {}", self.0);
  6. }
  7. }
  8. fn main() {
  9. let mut slot: Pin<&mut Tag> = pin!(Tag("舊"));
  10. slot.set(Tag("新"));
  11. println!("目前是 {}", slot.0);
  12. }

輸出:
  1. 丟棄 舊
  2. 目前是 新
  3. 丟棄 新

Unpin 與 PhantomPinned:哪些型別真的被釘住


Unpin 是自動特徵(auto trait):只要所有欄位都是 Unpin,結構就自動是 Unpin。想讓自己的型別「必須被釘住才能用」,就放一個 PhantomPinned 欄位,它不佔空間,但會讓整個型別失去 Unpin。
這時 Pin::new、get_mut 都不能用,只能用 Box::pin 或 pin! 釘住,並透過 get_ref(唯讀)或 as_ref 存取。async 區塊產生的 Future 一般也不是 Unpin。
簽名:
  1. pub struct PhantomPinned;
  2. impl<'a, T: ?Sized> Pin<&'a T> {
  3. pub const fn get_ref(self) -> &'a T
  4. }

範例:
  1. use std::marker::PhantomPinned;
  2. use std::pin::Pin;
  3. struct Anchor {
  4. label: String,
  5. _pin: PhantomPinned,
  6. }
  7. fn needs_unpin<T: Unpin>(_: &T) -> &'static str {
  8. "是 Unpin"
  9. }
  10. fn main() {
  11. let a: Pin<Box<Anchor>> = Box::pin(Anchor {
  12. label: String::from("固定點"),
  13. _pin: PhantomPinned,
  14. });
  15. let r: &Anchor = a.as_ref().get_ref();
  16. println!("{}", r.label);
  17. println!("String {}", needs_unpin(&r.label));
  18. println!("Pin<Box<Anchor>> {}", needs_unpin(&a));
  19. }

輸出:
  1. 固定點
  2. String 是 Unpin
  3. Pin<Box<Anchor>> 是 Unpin

最後一行說明:Anchor 本身不是 Unpin,但 Pin<Box<Anchor>> 這個「指標」是 Unpin,搬動指標不會移動堆積上的值。

重點整理


  • Pin<P> 承諾「被指向的值」不再移動,主要服務自我參照型別,尤其是 async 產生的 Future
  • Unpin 型別被釘住也沒有限制,可用 Pin::new、get_mut、Pin::into_inner 自由進出
  • 非 Unpin 型別用 Box::pin(堆積)或 pin!(堆疊)釘住;需要回傳或放進集合時選 Box::pin
  • 多次 poll 同一個 Future 時用 as_mut() 重新借出 Pin<&mut T>
  • 加入 PhantomPinned 欄位可讓自訂型別失去 Unpin;相關標記特徵見 std::marker