Pin: 不只是自引用——手动投影的艺术
构建自引用结构时Pin与unsafe的手动投影技术,以及如何安全地暴露字段 · 难度:入门 · +10XP
Pin: 不只是自引用——手动投影的艺术
Pin
use std::pin::Pin;
struct SelfRef {
data: String,
ptr: *const String, // 指向data
}
impl SelfRef {
fn new(data: String) -> Self {
SelfRef { ptr: std::ptr::null(), data }
}
fn init(self: Pin<&mut Self>) {
let this = unsafe { self.get_unchecked_mut() };
this.ptr = &this.data as *const String;
}
// 手动投影:获得data字段的Pin<&mut String>
fn pin_data(self: Pin<&mut Self>) -> Pin<&mut String> {
unsafe { self.map_unchecked_mut(|s| &mut s.data) }
}
}