Trying to understand the difference between Box::pin() and Pin::new_unchecked(). Suppose the following code:
use std::pin::Pin;
use std::marker::PhantomPinned;
struct Foo {
x: i32,
_pin: PhantomPinned,
}
fn bar() {
let fives = Foo {
x: 5,
_pin: PhantomPinned,
};
let mut boxed = Box::pin(fives);
unsafe {
let mut_ref: Pin<&mut Foo> = Pin::as_mut(&mut boxed);
Pin::get_unchecked_mut(mut_ref).x = 55;
}
println!("fives: {}", boxed.x);
// fives.x = 555; //Won't compile Box::pin() consumed fives.
let mut twos = Foo {
x: 2,
_pin: PhantomPinned,
};
let mut ptr = unsafe{ Pin::new_unchecked(&mut twos) };
unsafe {
let mut_ref: Pin<&mut Foo> = Pin::as_mut(&mut ptr);
Pin::get_unchecked_mut(mut_ref).x = 22;
}
println!("twos: {}", twos.x);
twos.x = 222;
println!("twos: {}", twos.x);
}
fn main() {
bar();
}
My understanding is that:
- The owners are
boxedandtwos, hencedrop()will be called on those when they go out of scope. drop()does not need to be manually implemented forFoo.fivesexists on the heap andtwosexists on the stack.
Is this correct? When is Box::pin() appropriate and when is Pin::new_unchecked() appropriate? When does drop() need to be implemented for a !Unpin struct?