Reference to generic trait with associated type as struct field

Could you please explain why Rust compiler do not see that StructA has TraitA implemented and therefore x satisfy to the requirements for the type of StructC::r ? How can I cast to the correct type explicitly ?

trait TraitA{}

trait TraitB{
    type As: TraitA;
}

struct StructA;

impl TraitA for StructA{}

struct StructB;

impl TraitB for StructB{
    type As = StructA;
}

struct StructC<'a> {
    r: &'a (dyn TraitB<As = (dyn TraitA)> + 'a),
}


fn main(){
    let x = StructB;
    let z = StructC {
        r: &x,
    };
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0271]: type mismatch resolving `<StructB as TraitB>::As == dyn TraitA`
  --> src/main.rs:25:12
   |
25 |         r: &x,
   |            ^^ expected struct `StructA`, found trait TraitA
   |
   = note: expected type `StructA`
              found type `dyn TraitA`
   = note: required for the cast to the object type `dyn TraitB<As = dyn TraitA>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0271`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

You can't nest trait objects like that.

If you change to

trait TraitB {
    type As: ?Sized;
}

impl TraitB for StructB{
    type As = dyn TraitA;
}

It will work, dyn Trait is a type just like StructA

2 Likes