我如何从rc< refcell< a a a a and and and;
我有我想用安全的生锈解决的设计问题,我找不到可行的解决方案。我不能使用 refcell
,因为您无法获得A&参考数据,仅 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&lt; revcell&lt; a&gt;&gt;
解决此问题,但是我受到限制在需要&amp; 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`
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果一个函数的参数为a type
&amp; a
的参数,则可以用对任何类型的引用来调用将其删除到a
的任何类型,其中包括<< 代码>&amp; ref&lt; a&gt; 。一种类型的删除对另一种类型的概念由deref
特质。这也是为什么可以使用
&amp; str
的函数使用&amp; string
(string:deref&lt; target = str = str&gt;
)的原因。 )。因此,如果将
a
保留为rc&lt; refcell&lt; a&gt;&gt;&gt;
,则可以像这样很容易地修复代码:请注意,此dereferences
a
a
/code>,然后 reborrows 它可以将其胁迫到特征对象。
If a function has an argument which is a of type
&A
, then you can call it with a reference to any type that dereferences toA
, which includes things like&Ref<A>
. The concept of one type dereferencing to another is captured by theDeref
trait. This is also the reason why a function that accepts&str
can be called with&String
(String: Deref<Target = str>
).So, if you keep
a
as aRc<RefCell<A>>
, you can fix your code quite easily like this:Note that this dereferences
A
and then reborrows it so that it can be coerced to a trait object.