# Pin - 解决 struct 自引用问题(内部一个成员是引用,指向另一个成员) - struct 被 move 走,但内部的引用无法重定向 - pin 的目标是一个指针(如`&T` 、`&mut T` 、`Box<T>`等),即 Pin 是一个指针容器 ```rust pub struct Pin<P> { pub pointer: P } ``` - `Pin::new()` 方法需要 P 实现 `Deref<Target: Unpin>` - `Pin::new_unchecked()` 方法需要 P 实现 `Deref` - 如何保证指针指向的值不被 move - `Pin::get_mut()` 需要 `T:Unpin` - `Pin::deref_mut()` 需要 `P:DerefMut<Target: Unpin>` - 因为如果指针指向的类型没有实现 `Unpin`,就无法获取到 `&mut T`,因此无法移动 T - 为 Future 等自引用结构实现 `!Unpin` ---- # Unpin marker - 几乎所有类型都自动实现了 `Unpin` trait - 实现了 `!Unpin` 的类型: - `async/await` 产生的 `Future` - `PhantomPinned` 和 含有它的结构体 - 例如在自引用结构体中包含它, 避免实现 `Unpin` -------- # pin-project ------ # Utils - `std::pin::pin!` - `tokio::pin!` - `pin_mut!` 在栈上安全地 pin 一个 value ------ # 参考资料 - [Rust 自引用结构、Pin 与 Unpin](https://zhuanlan.zhihu.com/p/600784379) - [Rust Pin、projections 与 pin-project](https://zhuanlan.zhihu.com/p/601775911)