【发布时间】:2020-09-10 07:35:57
【问题描述】:
这是我的代码:
use std::rc::{Rc, Weak};
use std::cell::RefCell;
trait Trait {}
fn push<E: Trait>(e: E) {
let mut v: Vec<Rc<RefCell<Box<dyn Trait>>>> = Vec::new();
// let x = Rc::new(RefCell::new(Box::new(e)));
// v.push(x); // error
v.push(Rc::new(RefCell::new(Box::new(e)))); // works fine
}
v.push(x) 引发此错误:
error[E0308]: mismatched types
--> src/main.rs:12:12
|
7 | fn push<E: Trait>(e: E) {
| - this type parameter
...
12 | v.push(x);
| ^ expected trait object `dyn Trait`, found type parameter `E`
|
= note: expected struct `std::rc::Rc<std::cell::RefCell<std::boxed::Box<dyn Trait>>>`
found struct `std::rc::Rc<std::cell::RefCell<std::boxed::Box<E>>>`
但是,如果我将值(使用完全相同的值和类型构造)直接推入向量中,它编译不会出错。
那么为什么第一个版本不能编译呢?我应该做些什么改变,以便在将其推入向量之前使用x?
【问题讨论】:
-
Rc<RefCell<Box<_>>>可能是不必要的;您通常可以使用Rc<RefCell<_>>侥幸逃脱。如果你删除Box层,both work 因为Rc<RefCell<T>>将强制转换为Rc<RefCell<dyn Trait>>,就像Box<T>一样。
标签: rust polymorphism traits parametric-polymorphism trait-objects