相关疑难解决方法(0)

为什么Rust不支持特征对象向上转换?

鉴于此代码:

trait Base {
    fn a(&self);
    fn b(&self);
    fn c(&self);
    fn d(&self);
}

trait Derived : Base {
    fn e(&self);
    fn f(&self);
    fn g(&self);
}

struct S;

impl Derived for S {
    fn e(&self) {}
    fn f(&self) {}
    fn g(&self) {}
}

impl Base for S {
    fn a(&self) {}
    fn b(&self) {}
    fn c(&self) {}
    fn d(&self) {}
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我不能投&Derived&Base:

fn example(v: &Derived) {
    v as &Base;
}
Run Code Online (Sandbox Code Playgroud)
error[E0605]: non-primitive cast: `&Derived` as `&Base`
  --> …
Run Code Online (Sandbox Code Playgroud)

oop language-design liskov-substitution-principle rust

40
推荐指数
4
解决办法
6616
查看次数

Downcasting和Box <Any>

pub struct WidgetWrap {
    // ...
    widget: RefCell<Box<Any>>,
}
Run Code Online (Sandbox Code Playgroud)

在某些时候,我想投Box<Any>Box<WidgetTrait>

let mut cell = widget.borrow_mut();
let w = cell.downcast_mut::<Box<WidgetTrait>>();
Run Code Online (Sandbox Code Playgroud)

这给了我这样的错误:

error: instantiating a type parameter with an incompatible type
`Box<WidgetTrait>`, which does not fulfill `'static` [E0144]
Run Code Online (Sandbox Code Playgroud)

这究竟意味着什么?

我看过如何解决:值可能包含引用; 添加`'static`绑定到`T`并尝试添加+ 'static到处.

pub struct WidgetWrap {
    // ...
    widget: RefCell<Box<Any + 'static>>,
}
let mut cell = widget.borrow_mut();
let w = cell.downcast_mut::<Box<WidgetTrait + 'static>>();
Run Code Online (Sandbox Code Playgroud)

它修复了编译错误,但是当我尝试打开如下所示的downcasrap框时失败.是的,盒子的内容是一个实现的对象WidgetTrait.

显然,我在Rust中的编码水平我不太了解,但也许有人可以帮助我更好地掌握上述任务中涉及的概念.

downcast rust

6
推荐指数
1
解决办法
3872
查看次数

在Rust回归时向上翻箱子

我有一个奇怪的问题:

trait A {}
trait B : A {}

struct MyStruct {}
impl A for MyStruct {}
impl B for MyStruct {}

fn fun_b() -> Box<B> {
    Box::new(MyStruct{})
}

fn fun_a() -> Box<A> {
    /*
    error: mismatched types [E0308]
    note: expected type `Box<A + 'static>`
    note:    found type `Box<B + 'static>`
    */
    fun_b()
}

fn main() {
    fun_a();
    fun_b();
}
Run Code Online (Sandbox Code Playgroud)

如果我替换fun_a为:

fn fun_a() -> Box<A> {
    Box::new(MyStruct{})
}
Run Code Online (Sandbox Code Playgroud)

(完全一样fun_b)

我需要在这里明确投射吗?为什么,更重要的是如何?

rust

5
推荐指数
0
解决办法
123
查看次数