![](/img/trans.png)
[英]How do I write generic code that accepts either a trait or a smart pointer to the trait (Box, Rc, etc)?
[英]How do I cast Rc<RefCell<ConcreteType>> to Rc<RefCell<dyn Trait>>?
我正在尝试将Rc<RefCell<Data>>
转换为Rc<RefCell<dyn Interface>>
( Data
实现Interface
)但在通用方法中是不可能的:
use std::cell::RefCell;
use std::rc::Rc;
trait Interface {
fn pouet(&self);
}
struct Data {}
impl Interface for Data {
fn pouet(&self) {
println!("pouet");
}
}
fn helper<T>(o: &Rc<RefCell<T>>)
where
T: Interface,
{
let t = o as &Rc<RefCell<dyn Interface>>;
work(t);
}
fn work(o: &Rc<RefCell<dyn Interface>>) {
o.borrow().pouet();
}
fn main() {
// work
{
let o = Rc::new(RefCell::new(Data {}));
work(&(o as Rc<RefCell<dyn Interface>>));
}
// raise an compile error
{
let o = Rc::new(RefCell::new(Data {}));
helper(&o);
}
}
我对非原始强制转换有一个编译错误:
error[E0605]: non-primitive cast: `&Rc<RefCell<T>>` as `&Rc<RefCell<dyn Interface>>`
--> src/main.rs:20:13
|
20 | let t = o as &Rc<RefCell<dyn Interface>>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
非常感谢,我明白了
解决方案是
fn helper<T>(o: &Rc<RefCell<T>>)
where
T: Interface + 'static,
{
let t = o.clone() as Rc<RefCell<dyn Interface>>;
work(&t);
}
或者
fn helper<T>(o: Rc<RefCell<T>>)
where
T: Interface + 'static,
{
let t = o as Rc<RefCell<dyn Interface>>;
work(&t);
}
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.