如何移动Vec< Box< dyn Trait>>进入Vec Rc RefCell dyn Trait>. [英] How to move a Vec<Box<dyn Trait>> Into Vec<Rc<RefCell<dyn Trait>>>
问题描述
我有 Vec< Box< dyn Trait>>
作为输入,我想将其元素存储在 Vec< Vc< Rc< RefCell< dyn Trait>>>中.
.最好的方法是什么?
I have a Vec<Box<dyn Trait>>
as input, and I want to store its elements in a Vec<Rc<RefCell<dyn Trait>>>
. What is the best way to do it?
我尝试过:
use std::cell::RefCell;
use std::rc::Rc;
trait Trait {}
fn main() {
let mut source: Vec<Box<dyn Trait>> = Vec::new();
let mut dest: Vec<Rc<RefCell<dyn Trait>>> = Vec::new();
for s in source {
let d = Rc::new(RefCell::new(s.as_ref()));
dest.push(d);
}
}
但是我得到了错误:
error[E0277]: the trait bound `&dyn Trait: Trait` is not satisfied
--> src/main.rs:12:19
|
12 | dest.push(d);
| ^ the trait `Trait` is not implemented for `&dyn Trait`
|
= note: required for the cast to the object type `dyn Trait`
实际上有可能还是我需要更改输入类型?
Is it actually possible or am I required to change the input type?
推荐答案
如果您控制 Trait
,一种选择是简单地通过 Box< dyn Trait>
实现它推迟到内部实现:
If you control Trait
, one option is to simply implement it for Box<dyn Trait>
by deferring to the inner implementation:
// We could implement Trait only for Box<dyn Trait>, but usually what you want
// is to implement it for all Boxes of things that are Trait instead
impl<T: ?Sized + Trait> Trait for Box<T> {}
fn pushes(dest: &mut Vec<Rc<RefCell<dyn Trait>>>, source: Vec<Box<dyn Trait>>) {
for s in source {
dest.push(Rc::new(RefCell::new(s)));
}
}
请注意,这会将已经 Box
的对象包装在第二个指针( Rc
)的后面,因此,如果您在表演中使用 dest
敏感算法,则必须将其取消引用两次,而不是一次.如果您能够重组代码以接受 Box< T:Trait>
,则可以通过将 T
从 Box移出来消除双重间接.
并放入 RefCell
.
Be aware this wraps the already-Box
ed object behind a second pointer (Rc
) so if you are using dest
in a performance-sensitive algorithm it will have to dereference it twice rather than once. If you are able to restructure the code so you can accept Box<T: Trait>
, you could eliminate the double indirection by moving the T
out of the Box
and into a RefCell
.
- 为什么除非使用临时变量,否则为什么不能插入dyn Trait的Vec?
- 如何通过Rc< RefCell< Box< MyStruct>>>到接受Rc< RefCell< Box< dyn MyTrait>>>>?a的函数(类似的情况,可以消除双向间接访问)
- 未实现大小调整"是什么?(解释为什么上面的示例中需要
?Sized
)
- Why can't I push into a Vec of dyn Trait unless I use a temporary variable?
- How do I pass Rc<RefCell<Box<MyStruct>>> to a function accepting Rc<RefCell<Box<dyn MyTrait>>>? (a similar case where the double indirection could be eliminated)
- What does "Sized is not implemented" mean? (explains why
?Sized
is needed in the above example)
这篇关于如何移动Vec< Box< dyn Trait>>进入Vec Rc RefCell dyn Trait>.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!