0

这段代码:

trait A {}

trait B: A {}

struct S;

impl A for S {}

impl B for S {}

fn main() {
    let s = S;
    let trait_obj_b: &B = &s;
    let trait_obj_a: &A = trait_obj_b;
} 

失败并出现错误:

error[E0308]: mismatched types
  --> src/main.rs:14:27
   |
14 |     let trait_obj_a: &A = trait_obj_b;
   |                           ^^^^^^^^^^^ expected trait `A`, found trait `B`
   |
   = note: expected type `&A`
              found type `&B`

为什么?既然B需要A,不应该所有的特征对象都&B自动实现&A吗?有没有办法在不更改特征定义或实现的情况下转换&B为?&A

操场

4

0 回答 0