How to represent invariance - code example

โš“ Rust    ๐Ÿ“… 2025-08-15    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 4      

surdeus

Hey, I'm going through subtyping and variance topic and I've got covariance and contravariance examples working, but I'm struggling to create a simple invariance example that actually fails to compile with the right error.

Here's what I have for the other two:

1. Covariance โ€” A type with a longer lifetime can be used where a shorter one is expected.

fn take_short<'short>(_x: &'short str) {}

fn main() {
    let long: &'static str = "hello";
    take_short(long); // &'static โ†’ &'short (covariant)
}

References are covariant in their lifetime โ€” you can โ€œshrinkโ€ lifetimes when passing them.

2. Contravariance โ€” Function parameter lifetimes flip direction.

fn call_with_static(f: fn(&'static str)) {
    f("hi");
}

fn accepts_any<'a>(_: &'a str) {} // shorter lifetime parameter

fn main() {
    call_with_static(accepts_any); // fn(&str) works as fn(&'static str)
}

What about invariance? Could you help me with some simple example which fails with correct error?

2 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed