I am trying to cast Rc<RefCell<Data>>
to Rc<RefCell<dyn Interface>>
( Data
implements Interface
) but it's impossible in a generic method:
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);
}
}
I have an compile error on non-primitive cast :
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
many thanks, i understand
the solutions are
fn helper<T>(o: &Rc<RefCell<T>>)
where
T: Interface + 'static,
{
let t = o.clone() as Rc<RefCell<dyn Interface>>;
work(&t);
}
or
fn helper<T>(o: Rc<RefCell<T>>)
where
T: Interface + 'static,
{
let t = o as Rc<RefCell<dyn Interface>>;
work(&t);
}
Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.