Arbitary Lifetime Transmutation via Rust Unsoundness
Do you believe that one can write a function in safe Rust which can arbitrarily change the lifetime of a reference? For clarity, try to implement the following function without using unsafe
:
fn transmute_lifetime<'a, 'b>(x: &'a u64) -> &'b u64 { todo!() }
Such intention seems to violate the fundamental principle of Rust’s lifetime system, which is to prevent dangling references and data. However, it is possible to write such a function in safe Rust, and it is not even that hard:
trait Trait {
type Output;
}
impl<T: ?Sized> Trait for T {
type Output = &'static u64;
}
fn foo<'a, T: ?Sized>(x: <T as Trait>::Output) -> &'a u64 { x }
fn transmute_lifetime<'a, 'b>(x: &'a u64) -> &'b u64 {
foo::<dyn Trait<Output=&'a u64>>(x)
}