问题描述
我有以下定义:
trait A {
fn f(&self);
}
trait B: A {
// ...
}
我想实现这种功能:
fn convert(v: Rc<RefCell<dyn B>>) -> Rc<RefCell<dyn A>> {
}
我想要一种方法来返回共享同一对象的值,这意味着使用以下声明:
let x: Rc<RefCell<dyn B>> /* = ... */;
let y = convert(Rc::clone(&x));
我如何实现函数convert
或如何更改类型定义以具有该行为和这种转换(转换为子对象)。
解决方法
Rust不支持特征对象的直接向上转换。由于特质对象的实现方式,没有运行时的额外工作是不可能的,因此Rust使您自己完成工作。
您可以像这样
"source node name","destination node name","application name","reason","interface number","channel number allocated"
,
感谢您的想法,我决定采用折衷方法,根据Rust规则,避免使用特征对象作为函数convert
的参数:
use std::rc::Rc;
use std::cell::RefCell;
trait A {
fn print(&self);
}
trait B: A {
}
trait Convert {
fn convert(it: Rc<RefCell<Self>>) -> Rc<RefCell<dyn A>>;
}
struct MyType(u32);
impl Convert for MyType {
fn convert(it: Rc<RefCell<Self>>) -> Rc<RefCell<dyn A>> {it}
}
impl A for MyType {
fn print(&self) {
println!("MyType({}) as A",self.0);
}
}
impl B for MyType {}
fn main() {
let a: Rc<RefCell<dyn A>>;
{
let b = Rc::new(RefCell::new(MyType(3)));
a = Convert::convert(b.clone());
}
a.borrow().print();
}