Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: How to represent invariance - code example
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:
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.
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