Skip to content

Instantly share code, notes, and snippets.

@ClarkeRemy
Last active April 24, 2025 07:27
Show Gist options
  • Save ClarkeRemy/622b200c24148d92bd7f0a7068c56807 to your computer and use it in GitHub Desktop.
Save ClarkeRemy/622b200c24148d92bd7f0a7068c56807 to your computer and use it in GitHub Desktop.
rust lifetime variance (fail mains does note compile)
use std::marker::PhantomData;
// CONTRAVARIANT
struct Contra<'contra> (PhantomData<
fn(&'contra ()) -> ()
>);
// succeeds (contravariant "lengthening")
fn contra_1<'a>( contra : Contra<'a>) -> Contra<'static> {
contra
}
// fails
fn contra_2<'a>( contra : Contra<'static>) -> Contra<'a>
{
contra
}
// COVARIANT
struct Co<'co> (PhantomData<
fn() -> &'co ()
>);
// fails
fn co_1<'a>( co : Co<'a>) -> Co<'static> {
co
}
// succeeds (covariant "shortening")
fn co_2<'a>( co : Co<'static>) -> Co<'a>
{
co
}
// INVARIANT
struct Inv<'inv> (PhantomData<
fn(&'inv ()) -> &'inv ()
>);
// fails
fn inv_1<'a>( inv : Inv<'a>) -> Inv<'static> {
inv
}
// fails
fn inv_2<'a>( inv : Inv<'static>) -> Inv<'a>
{
inv
} // succeeds (invariant "same")
fn inv_3<'a>( inv : Inv<'a>) -> Inv<'a>
{
inv
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment