首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从Rc<RefCell<A>>获得&A引用?

如何从Rc<RefCell<A>>获得&A引用?
EN

Stack Overflow用户
提问于 2018-09-01 00:44:19
回答 1查看 2.9K关注 0票数 11

我有设计问题,我想解决与安全锈蚀,我还没有找到一个可行的解决方案。我不能使用RefCell,因为您不能获得对数据的引用,只有Ref / RefMut

这是一个删除不相关字段/方法的简化示例

代码语言:javascript
复制
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的库之外。

这会产生错误:

代码语言:javascript
复制
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`
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-01 01:29:04

如果一个函数有一个类型为&A的参数,那么您可以调用它,引用任何取消引用到A的类型,其中包括&Ref<A>之类的内容。一种类型去引用另一种类型的概念被Deref特性所捕获。这也是为什么接受&str的函数可以用&String (String: Deref<Target = str>)调用的原因。

因此,如果将a保持为Rc<RefCell<A>>,则可以很容易地修复代码,如下所示:

代码语言:javascript
复制
library_struct.function(&*self.a.borrow());

请注意,这个取消A,然后再借用它,以便它可以被胁迫到一个特征对象。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52124007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档