相关疑难解决方法(0)

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
查看次数

为什么不能将&amp;&amp;(Sized + Trait)强制转换为&dyn Trait?

在下面的代码中,不可能从对实现相同特征的动态大小类型的引用中获得对特征对象的引用。为什么会这样呢?究竟是什么区别&dyn Trait&(?Sized + Trait)我是否可以使用这两种调用方法特质?

实现的类型FooTraitContainerTrait可能例如具有type Contained = dyn FooTraittype Contained = T在哪里T实现的具体类型FooTrait。在这两种情况下,都很难获得&dyn FooTrait。我想不出另一种情况,这是行不通的。为什么在通用情况下这不可能FooTraitContainerTrait

trait FooTrait {
    fn foo(&self) -> f64;
}

///

trait FooTraitContainerTrait {
    type Contained: ?Sized + FooTrait;
    fn get_ref(&self) -> &Self::Contained;
}

///

fn foo_dyn(dyn_some_foo: &dyn FooTrait) -> f64 {
    dyn_some_foo.foo()
}

fn foo_generic<T: ?Sized + FooTrait>(some_foo: &T) -> f64 {
    some_foo.foo()
}

///

fn foo_on_container<C: FooTraitContainerTrait>(containing_a_foo: &C) -> …
Run Code Online (Sandbox Code Playgroud)

generics polymorphism rust trait-objects

5
推荐指数
1
解决办法
168
查看次数

标签 统计

rust ×2

downcast ×1

generics ×1

polymorphism ×1

trait-objects ×1