gpt4 book ai didi

generics - 如何将 Rc> 转换为 Rc>?

转载 作者:行者123 更新时间:2023-12-03 11:25:15 27 4
gpt4 key购买 nike

我正在尝试转换 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
playground

最佳答案

非常感谢,我明白了
解决方案是

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);
}
谢谢

关于generics - 如何将 Rc<RefCell<ConcreteType>> 转换为 Rc<RefCell<dyn Trait>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65495270/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com