相关疑难解决方法(0)

如何将盒装特征转换为特征参考?

我有以下代码尝试从盒装特征中引用特征对象:

trait T {}

struct S {}

impl T for S {}

fn main() {
    let struct_box: Box<S> = Box::new(S {});
    let struct_ref: &S = &struct_box;

    let trait_box: Box<T> = Box::new(S {});
    let trait_ref: &T = &trait_box;
}
Run Code Online (Sandbox Code Playgroud)

编译器返回以下错误:

error[E0277]: the trait bound `std::boxed::Box<T>: T` is not satisfied
  --> src/main.rs:12:25
   |
12 |     let trait_ref: &T = &trait_box;
   |                         ^^^^^^^^^^ the trait `T` is not implemented for `std::boxed::Box<T>`
   |
   = note: required for the cast to the object type `T` …
Run Code Online (Sandbox Code Playgroud)

rust

3
推荐指数
2
解决办法
548
查看次数

标签 统计

rust ×1