首页 > 解决方案 > Rust:将特征对象转换为不同的类型

问题描述

有什么方法可以安全地将特征对象(dyn A)转换为另一种类型(dyn B)?

trait A {}
trait B: A {}
impl <T: A> B for T {}

fn cast(x: &dyn A) -> &dyn B {
  x
}
error[E0308]: mismatched types
 --> src/lib.rs:6:3
  |
6 |   x
  |   ^ expected trait `B`, found trait `A`
  |
  = note: expected type `&dyn B`
             found type `&dyn A`

标签: rust

解决方案


推荐阅读