【问题标题】:How can I return a reference to a sub-element of a nested entry in a structure?如何返回对结构中嵌套条目的子元素的引用?
【发布时间】:2019-05-28 10:11:24
【问题描述】:

我有一个带有其他结构向量的结构:

pub struct StructB {
    value1: u64,
    value2: String,
}

pub struct StructA {
    array: Vec<StructB>,
}

StructB 是常量;在创建StructA 期间,array 中填充了从文件中读取且不太可能被修改的对象。

我想要一个函数来获取与输入参数对应的元素StructBget_structB(input: u64) -&gt; &amp;StructB。为简单起见,假设其他人正在检查边界,我们将只返回具有给定索引的元素。

我很纠结如何在 Rust 中实现它。我想返回一种“只读”引用或对不可变但不复制的对象的引用。我想不出正确的方法来做到这一点。

impl StructA {
    fn get_structB(&self, idx: u64) -> Box<StructB> {   // Or should I use here Rc?
        // Here I don't want to consume self just return reference wrapped to the idx element
        // Should I implement something like as_ref() for the StructA?
        self.array[idx]     // That of course won't compile
    }
}

【问题讨论】:

  • 你为什么不用fn get_structB(&amp;self, idx: usize) -&gt; Option&lt;&amp;StructB&gt; { self.array.get(idx) }
  • @hellow,他可能想将该变量发送到某个可能想要拥有数据本身的线程。 Rc 在这种情况下很有用
  • 没关系。只要您只想要只读访问权限,您就可以传递&amp;StructBRC 这里不需要恕我直言。
  • 是的,我认为在这里引用选项应该没问题。只是不同的 Rust Wrappers 的数量让我多次思考应该在哪里使用什么。选项给了我一些与 Enum 之类的关联?所以这就是为什么我开始思考智能指针之类的东西。
  • @Mazeryt 在对象没有明确的“所有者”时使用Rc/Arc。感觉会更OO,因为它本质上是添加了一个简单的GC。

标签: rust ownership


【解决方案1】:
impl StructA {
    fn get_structB(&self, i: usize) -> &StructB {
        return &self.array[i];
    }
}

这可以解决问题。但是,如果您编写以下代码,您可能会遇到一些问题:

// `a` is a StructA instance
let bb = a.get_struct_b(0);
println!("{:?}", bb);
drop(a);              // move out of `a` occurs here
println!("{:?}", bb); // borrow of `a` is used here

您必须修改结构定义并使用Rc 来编写函数。 Rc 引入了一点性能影响,并使代码更复杂,因此您可能希望仅在知道移动 StructA 后将使用数据时才使用它。

pub struct StructA {
    array: Vec<Rc<StructB>>,
}

impl StructA {
    fn get_structB(&self, i: usize) -> Rc<StructB> {
        return Rc::clone(self.array[i]);
    }
}

【讨论】:

  • 顺便说一句,在块的末尾使用显式的return 不是惯用的 Rust。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
  • 2018-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
相关资源
最近更新 更多