How to represent invariance - code example
โ Rust ๐ 2025-08-15 ๐ค surdeus ๐๏ธ 10Hey, 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
๐ท๏ธ Rust_feed