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?