Hello, that code will not compile if there would be no PhantomData
, but will compile if I use PhantomData
. Can you please explain me, why?
trait Erase {}
impl<T> Erase for T {}
// Compiles like this:
struct Handle<'a>(std::marker::PhantomData<Box<dyn Erase + 'a>>);
// Not compiles like this:
// struct Handle<'a>(Box<dyn Erase + 'a>);
fn wrap<'a, F: FnOnce() + 'a>(_: F) -> Handle<'a> {
todo!()
}
fn main() {
let mut number = 3;
let (tx, rx) = std::sync::mpsc::channel();
tx.send(&mut number).unwrap();
drop(tx);
let _handle = wrap(move || drop(rx));
core::hint::black_box(number);
}
You dont even need Erase
to trigger it, these definitions are enough:
struct Handle<'a>(std::marker::PhantomData<std::sync::mpsc::Receiver<&'a mut i32>>);
struct Handle<'a>(std::sync::mpsc::Receiver<&'a mut i32>);
It feels like a Rust bug to be honest... Isn't it the whole purpose of PhantomData<T>
to make type behave like it has T
inside?