What is subtyping on T

like the code below,
if T1 is a subtype of T2,
then what is T1?

trait A {
    fn a(self);
}


trait B: A {
    fn b(self);
}

struct C {
    i: i32
}

impl A for C {
    fn a(self){}
}

impl B for C {
    fn b(self){}
}

T1 == C? the following code passes compiling which conflict with &mut T invarince rule;

fn test(d: &mut A) {}

fn main() {
    let mut x = C {
        i: 0
    };
    test(&mut x);
}

T1 == B? the following code failed to pass compiling which conflict with &T covarince rule;

fn test(d: &A) {}

fn main() {
    let mut x = C {
        i: 0
    };
    test(&x as &B);
}

There is no sub typing relation for traits and trait up casting is not implemented yet (but there is work in progress right now)

the chapter does not say T's varince is not present, instead it lists rule on T, e.g. the rules is future rules?

*	&'a mut T	covariant	invariant

Traits and structs doesn't have subtype relationship, but the lifetime does. If the lifetime 'a includes 'b, the 'a is a subtype of the 'b. This means &'c &'a i32 can be coerced to &'c &'b i32 as the &T is covariant over T, but &'c mut &'a i32 cannot be coerced to &'c mut &'b i32 as &mut T is invariant over T.

1 Like

so, why is the rule includes the T Could it be the following:
&'a is covarince, but 'a mut is invarince

This is so that &mut &'a T is invariant in 'a. Remember, generic parameters can have lifetime parameters when they are substituted for concrete types.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.