0

是否可以向上转换Rc<dyn Foo>?如果不是,为什么不呢?

use std::rc::Rc;

trait Bar {}
trait Foo: Bar {}

fn upcast(this: Rc<dyn Foo>) -> Rc<dyn Bar> {
    this
}

结果是

error[E0308]: mismatched types
  --> src/core/mod.rs:20:5
   |
19 | fn upcast(this: Rc<dyn Foo>) -> Rc<dyn Bar> {
   |                                 ----------- expected `Rc<(dyn Bar + 'static)>` because of return type
20 |     this
   |     ^^^^ expected trait `Bar`, found trait `Foo`
   |
   = note: expected struct `Rc<(dyn Bar + 'static)>`
              found struct `Rc<(dyn Foo + 'static)>`
4

0 回答 0