如何将trait对象转换为“sub-trait”对象?

时间:2018-04-24 14:23:49

标签: rust trait-objects

此代码:

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

Playground

0 个答案:

没有答案