我有设计问题,我想解决与安全锈蚀,我还没有找到一个可行的解决方案。我不能使用RefCell,因为您不能获得对数据的引用,只有Ref / RefMut。
这是一个删除不相关字段/方法的简化示例
use std::cell::RefCell;
use std::rc::Rc;
struct LibraryStruct {}
impl LibraryStruct {
fn function(&self, _a: &TraitFromLibrary) {}
}
trait TraitFromLibrary {
fn trait_function(&self, library_struct: LibraryStruct);
}
// I don't want to copy this, bad performance
struct A {
// fields...
}
impl TraitFromLibrary for A {
fn trait_function(&self, library_struct: LibraryStruct) {
// custom A stuff
}
}
// B manipulates A's in data
struct B {
data: Vec<A>,
}
struct C {
// This type doesn't have to be & for solution. C just needs immutable access
a: Rc<RefCell<A>>,
}
impl<'a> TraitFromLibrary for C {
fn trait_function(&self, library_struct: LibraryStruct) {
// custom C stuff
// Takes generic reference &, this is why Ref / RefCell doesn't work
library_struct.function(&self.a.borrow());
}
}
// B and C's constructed in Container and lifetime matches Container
// Container manipulates fields b and c
struct Container {
b: B,
c: Vec<C>,
}
fn main() {}我可以用Rc<RefCell<A>>来解决这个问题,但是我被限制在需要&A的库之外。
这会产生错误:
error[E0277]: the trait bound `std::cell::Ref<'_, A>: TraitFromLibrary` is not satisfied
--> src/main.rs:33:33
|
33 | library_struct.function(&self.a.borrow());
| ^^^^^^^^^^^^^^^^ the trait `TraitFromLibrary` is not implemented for `std::cell::Ref<'_, A>`
|
= note: required for the cast to the object type `TraitFromLibrary`发布于 2018-09-01 01:29:04
如果一个函数有一个类型为&A的参数,那么您可以调用它,引用任何取消引用到A的类型,其中包括&Ref<A>之类的内容。一种类型去引用另一种类型的概念被Deref特性所捕获。这也是为什么接受&str的函数可以用&String (String: Deref<Target = str>)调用的原因。
因此,如果将a保持为Rc<RefCell<A>>,则可以很容易地修复代码,如下所示:
library_struct.function(&*self.a.borrow());请注意,这个取消A,然后再借用它,以便它可以被胁迫到一个特征对象。
https://stackoverflow.com/questions/52124007
复制相似问题