繁体   English   中英

如何为包含Rc的结构实现Deref <Refcell<Trait> &gt;?

[英]How can I implement Deref for a struct that holds an Rc<Refcell<Trait>>?

我的目标是将针对我的结构的方法调用委托给Trait的方法,其中Trait对象位于RefCellRc中。

我试图遵循以下问题的建议: 如何从Rc <RefCell <A >>获取&A参考?

我收到一个编译错误。

use std::rc::Rc;
use std::cell::RefCell;
use std::fmt::*;
use std::ops::Deref;

pub struct ShyObject {
    pub association: Rc<RefCell<dyn Display>>
}

impl Deref for ShyObject {
    type Target = dyn Display;
    fn deref<'a>(&'a self) -> &(dyn Display + 'static) {
        &*self.association.borrow()
    }
}

fn main() {}

这是错误:

error[E0515]: cannot return value referencing temporary value
  --> src/main.rs:13:9
   |
13 |         &*self.association.borrow()
   |         ^^-------------------------
   |         | |
   |         | temporary value created here
   |         returns a value referencing data owned by the current function

我的示例使用Display作为特征。 实际上,我有很多方法的特质。 我试图避免必须实现所有这些方法的样板,而只是在每个调用中探究Trait对象。

你不能 RefCell::borrow返回Ref<T> ,而不是&T 如果尝试使用方法来执行此操作,则需要首先借用Ref<T>但它会超出范围。

除了实现Deref ,您还可以使用一个方法返回执行Deref的方法:

impl ShyObject {
    fn as_deref(&self) -> impl Deref<Target = dyn Display> {
        self.association.borrow()
    }
}

否则,由于无论如何您只想公开内部数据的Display实现,因此可以通过实际取消引用委托的其他类型来解决此问题:

pub struct ShyObject {
    association: Assocation<dyn Display>,
}

struct Assocation<T: ?Sized>(Rc<RefCell<T>>);

impl<T: Display + ?Sized> fmt::Display for Assocation<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0.borrow())
    }
}

impl Deref for ShyObject {
    type Target = dyn Display + 'static;
    fn deref(&self) -> &Self::Target {
        &self.association
    }
}

你不能这样做。 borrow创建一个新的结构 ,该结构允许RefCell跟踪借位。 然后,您将不允许向此Ref返回借用,因为它是局部变量。

如何创建 Rc <refcell< to something that already exists?< div><div id="text_translate"><p> 因此,为了自学一些 Rust,我决定创建一个我喜欢的简单混合数据类型 ChainVec。 这是一个向量的双向链接列表,如果您需要调整可能增长到巨大规模的向量的大小,这很有用。 它使用链表逻辑,但查找、搜索和迭代特性要快得多,因为它们的增长时间为 O(n/alot)。 不过,这并不是重点:我遇到的问题会出现在任何双向链表中。</p><p> 这就是问题所在......在 C 中,当我创建新的链表节点时,我可以将其“尾部”设置为指向前一个节点的指针。 我可以在 C 中像糖果一样扔指针,但在 Rust 中,我还不知道如何创建新指针。 这是我尝试过的...(在 fn push_head 下查找无效行)</p><p> 注意:在我的实现中,chainvec 的“头”节点是您选择指向的任何一个,因此列表头/尾没有单独的结构。</p><pre> #[allow(non_snake_case)] use std::{cell::RefCell, rc::Rc}; #[allow(dead_code)] struct ChainVec&lt;T&gt; { item: Option&lt;Vec&lt;T&gt;&gt;, head: Option&lt;Rc&lt;RefCell&lt;ChainVec&lt;T&gt;&gt;&gt;&gt;, tail: Option&lt;Rc&lt;RefCell&lt;ChainVec&lt;T&gt;&gt;&gt;&gt;, } impl&lt;T&gt; ChainVec&lt;T&gt; { fn new(prealloc: usize) -&gt; Self { let vector: Vec&lt;T&gt; = Vec::with_capacity(prealloc); Self { item: Some(vector), head: None, tail: None, } } fn new_with_links(prealloc: usize, head: Option&lt;Rc&lt;RefCell&lt;ChainVec&lt;T&gt;&gt;&gt;&gt;, tail: Option&lt;Rc&lt;RefCell&lt;ChainVec&lt;T&gt;&gt;&gt;&gt;) -&gt; Self { let vector: Vec&lt;T&gt; = Vec::with_capacity(prealloc); Self { item: Some(vector), head: head, tail: tail, } } fn push_head(&amp;mut self, prealloc: usize) { self.head = Some(Rc::new(RefCell::new(ChainVec::new_with_links(prealloc, None, Some(Rc::new(RefCell::new(self))))))); } } #[allow(unused_variables)] fn main() { let alef: ChainVec&lt;u32&gt; = ChainVec::new(100); println,("Hello; world!"); }</pre><p> 显然,当我尝试通过 Some(Rc::new(RefCell::new(self))) 在 push_head 中创建一个新指针时,我迷路了。 我有</p><pre>mismatched types expected struct `ChainVec&lt;T&gt;` found mutable reference `&amp;mut ChainVec&lt;T&gt;`</pre><p> 取消引用运算符在这里不做任何事情......我不知道如何继续。</p><p> 如何创建对已经存在的结构的 Rc&lt;RefCell&lt; 引用? </p></div></refcell<>

[英]How can I create an Rc<RefCell< to something that already exists?

暂无
暂无

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

相关问题 如何使用 Rc 的数据类型<refcell<t> &gt; 在结构中? </refcell<t> 向下转换 Rc <refcell<box<struct> &gt;&gt; 到 Rc <refcell<box<dyn trait> &gt;&gt; </refcell<box<dyn></refcell<box<struct> 我如何施放 Rc <refcell<concretetype> &gt; 到 Rc <refcell<dyn trait> &gt;? </refcell<dyn></refcell<concretetype> 如何从 Rc 获得 &amp;A 参考<RefCell<A> &gt;? 如何创建 Rc <refcell< to something that already exists?< div><div id="text_translate"><p> 因此,为了自学一些 Rust,我决定创建一个我喜欢的简单混合数据类型 ChainVec。 这是一个向量的双向链接列表,如果您需要调整可能增长到巨大规模的向量的大小,这很有用。 它使用链表逻辑,但查找、搜索和迭代特性要快得多,因为它们的增长时间为 O(n/alot)。 不过,这并不是重点:我遇到的问题会出现在任何双向链表中。</p><p> 这就是问题所在......在 C 中,当我创建新的链表节点时,我可以将其“尾部”设置为指向前一个节点的指针。 我可以在 C 中像糖果一样扔指针,但在 Rust 中,我还不知道如何创建新指针。 这是我尝试过的...(在 fn push_head 下查找无效行)</p><p> 注意:在我的实现中,chainvec 的“头”节点是您选择指向的任何一个,因此列表头/尾没有单独的结构。</p><pre> #[allow(non_snake_case)] use std::{cell::RefCell, rc::Rc}; #[allow(dead_code)] struct ChainVec&lt;T&gt; { item: Option&lt;Vec&lt;T&gt;&gt;, head: Option&lt;Rc&lt;RefCell&lt;ChainVec&lt;T&gt;&gt;&gt;&gt;, tail: Option&lt;Rc&lt;RefCell&lt;ChainVec&lt;T&gt;&gt;&gt;&gt;, } impl&lt;T&gt; ChainVec&lt;T&gt; { fn new(prealloc: usize) -&gt; Self { let vector: Vec&lt;T&gt; = Vec::with_capacity(prealloc); Self { item: Some(vector), head: None, tail: None, } } fn new_with_links(prealloc: usize, head: Option&lt;Rc&lt;RefCell&lt;ChainVec&lt;T&gt;&gt;&gt;&gt;, tail: Option&lt;Rc&lt;RefCell&lt;ChainVec&lt;T&gt;&gt;&gt;&gt;) -&gt; Self { let vector: Vec&lt;T&gt; = Vec::with_capacity(prealloc); Self { item: Some(vector), head: head, tail: tail, } } fn push_head(&amp;mut self, prealloc: usize) { self.head = Some(Rc::new(RefCell::new(ChainVec::new_with_links(prealloc, None, Some(Rc::new(RefCell::new(self))))))); } } #[allow(unused_variables)] fn main() { let alef: ChainVec&lt;u32&gt; = ChainVec::new(100); println,("Hello; world!"); }</pre><p> 显然,当我尝试通过 Some(Rc::new(RefCell::new(self))) 在 push_head 中创建一个新指针时,我迷路了。 我有</p><pre>mismatched types expected struct `ChainVec&lt;T&gt;` found mutable reference `&amp;mut ChainVec&lt;T&gt;`</pre><p> 取消引用运算符在这里不做任何事情......我不知道如何继续。</p><p> 如何创建对已经存在的结构的 Rc&lt;RefCell&lt; 引用? </p></div></refcell<> 如何在具有生命周期的结构上实现标记特征? 如何为枚举实现Borrow,ToOwned或Deref? 如何在包含锈特质的泛型类型上实现deref? 将RefCell和Rc包装为结构类型 如何使用具有 Deref 特征的多态性来获得可以由事务或连接表示的单个 object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM