Last active
July 26, 2022 15:40
-
-
Save VigneshChennai/5a56c8ad4ed563c820f37e5cea8ecb88 to your computer and use it in GitHub Desktop.
Covariant and Invariant - Rust Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct CovariantExample<'a, T> { | |
a: &'a T | |
} | |
struct InvariantExample<'a, T> { | |
a: &'a mut T | |
} | |
fn covarient() { | |
let a = 1; | |
let v2: &i32 = &a; | |
let c1 = CovariantExample::<&'static i32> {a: &&1}; | |
let c2 = CovariantExample::<&i32> {a: &v2}; | |
let mut c3 = &c2; | |
c3 = &c1; // ==> This will works as CovariantExample<T> is covariant to T | |
} | |
fn invarient() { | |
let a = 1; | |
let mut v2: &i32 = &a; | |
let c1 = InvariantExample::<&'static i32> {a: &mut &1 }; | |
let c2 = InvariantExample::<&i32> {a: &mut v2}; | |
let mut c3 = &c2; | |
// the below will fail to compile | |
c3 = &c1; // ==> This will fail to compile as InvariantExample<T> is invariant to T | |
} | |
fn main() { | |
covarient(); | |
invarient(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The compilation fails with the compiler complaining about "variable a 'not live long enough'"
It is due to the reason that, due to the line 34, the compile tries to make
c2
type asInvariantExample<&'static i32>
. It does it becauseInvariantExample<T>
is invariant over T. So, it can't passInvariantExample::<&'static i32>
whereInvariantExample::<&i32>
is needed.PS: