简体   繁体   English

我如何施放 Rc <refcell<concretetype> &gt; 到 Rc <refcell<dyn trait> &gt;? </refcell<dyn></refcell<concretetype>

[英]How do I cast Rc<RefCell<ConcreteType>> to Rc<RefCell<dyn Trait>>?

I am trying to cast Rc<RefCell<Data>> to Rc<RefCell<dyn Interface>> ( Data implements Interface ) but it's impossible in a generic method:我正在尝试将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);
    }
}

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

playground 操场

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谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写接受特征或指向特征的智能指针(Box、Rc 等)的通用代码? - How do I write generic code that accepts either a trait or a smart pointer to the trait (Box, Rc, etc)? 为什么我不能在 Rc 中使用这个闭包<dyn Fn()> ? - Why can't I use this closure inside a Rc<dyn Fn()>? 如何从RefCell借用T. <T> 作为参考? - How to borrow the T from a RefCell<T> as a reference? 为什么不能将 `&amp;(?Sized + Trait)` 转换为 `&amp;dyn Trait`? - Why can't `&(?Sized + Trait)` be cast to `&dyn Trait`? 为什么我不能用 let _: Arc 创建一个特征 object<dyn trait> = value.into()?</dyn> - Why can't I create a trait object with let _: Arc<dyn Trait> = value.into()? Scala:如何设置通用特征? - Scala: How do I set a generic Trait? 如何从特征函数返回任意类型的迭代器? - How do I return an iterator of arbitrary type from a trait function? 如何为类型引用的操作指定通用特征? - How do I specify a generic trait for operations on references to types? 如何构造可能实现特征的许多潜在结构中的任何一个? - How do I construct any of potentially many structs that implement a trait? 你如何归还收藏品 <ConcreteType> 作为一个集合 <Interface> ? - How can you return a Collection<ConcreteType> as a Collection<Interface>?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM