Skip to main content

CovariantForLt

Trait CovariantForLt 

Source
pub unsafe trait CovariantForLt: ForLt {
    // Provided method
    fn cast_ref<'r, 'short: 'r, 'long: 'short>(
        long: &'r Self::Of<'long>,
    ) -> &'r Self::Of<'short> { ... }
}
Expand description

ForLt subtrait for types that are covariant over their lifetime parameter.

Provides a safe cast_ref method for types that are proven to be covariant. The CovariantForLt! macro syntax is the same as ForLt!.

§Macro

It is not recommended to implement this trait directly. CovariantForLt! macro is provided to obtain a type that implements this trait.

The full syntax is

CovariantForLt!(for<'a> TypeThatUse<'a>)

which gives a type so that <CovariantForLt!(for<'a> TypeThatUse<'a>) as CovariantForLt>::Of<'b> is TypeThatUse<'b>.

You may also use a short-hand syntax which works similar to lifetime elision. The macro also accepts types that do not involve a lifetime at all.

CovariantForLt!(TypeThatUse<'_>) // Equivalent to `CovariantForLt!(for<'a> TypeThatUse<'a>)`.
CovariantForLt!(&u32) // Equivalent to `CovariantForLt!(for<'a> &'a u32)`.
CovariantForLt!(u32) // Equivalent to `CovariantForLt!(for<'a> u32)`.

The macro will attempt to prove that the type is indeed covariant over the lifetime supplied. When it cannot be syntactically proven, it will emit checks to ask the Rust compiler to prove it.

CovariantForLt!(fn(&u32)) // Contravariant, will fail compilation.

There is a limitation if the type refers to generic parameters; if the macro cannot prove the covariance syntactically, the emitted checks will fail the compilation as it needs to refer to the generic parameter but is in a separate item.

fn expect_lt<F: CovariantForLt>() {}
fn generic_fn<T: 'static>() {
    // Syntactically proven by the macro
    expect_lt::<CovariantForLt!(&T)>();
    // Syntactically proven by the macro
    expect_lt::<CovariantForLt!(&KBox<T>)>();
    // Cannot be syntactically proven, need to check covariance of `KBox`
    // expect_lt::<CovariantForLt!(&KBox<&T>)>();
}

§Safety

Self::Of<'a> must be covariant over the lifetime 'a.

Provided Methods§

Source

fn cast_ref<'r, 'short: 'r, 'long: 'short>( long: &'r Self::Of<'long>, ) -> &'r Self::Of<'short>

Cast a reference to a shorter lifetime.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl<const SIZE: usize> CovariantForLt for Bar<'static, SIZE>

Source§

impl<const SIZE: usize> CovariantForLt for ExclusiveIoMem<'static, SIZE>

Source§

impl<const SIZE: usize> CovariantForLt for IoMem<'static, SIZE>