如何提供对同级结构的引用? [英] How can I provide a reference to a struct that is a sibling?

查看:30
本文介绍了如何提供对同级结构的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些共享不可变数据的结构,还有另一个使用该数据的结构.我想把这些打包成一种结构,因为它们在一起具有逻辑意义.但是,我不明白我如何提供对对象本身的引用施工期间:

I have a structure with some shared immutable data, and another structure that makes use of that data. I'd like to bundle these into one structure because they make logical sense together. However, I don't understand how I can provide a reference to the object itself during construction:

struct A {
    v: i32,
}
struct B<'a> {
    a: &'a A,
    b: i32,
}

struct C<'a> {
    a: A,
    b: B<'a>,
}

fn main() {
    C {
        a: A { v: 13 },
        b: B { a: &??, b: 17 },
    }
}

推荐答案

为了扩展 Chris 的回答,有两个问题需要解决:

To expand on Chris' answer, there are two issues to solve:

  1. 具有明确允许引用同级的语法
  2. 设置以便仍然可以验证借用规则

覆盖(1)相对容易,例如可以使用一个简单的&self.a,将self锚定在尽可能最外层的类型中;然而,覆盖 (2) 似乎要困难得多:结构本身没有任何内容指向这种关系,因此 self.a 被借用并不明显.

It is relatively easy to cover (1), a simple &self.a could be used for example, anchoring self in the most outer type possible; however it seems that covering (2) would be much more difficult: nothing in the structure itself points to this relationship, and therefore it is not evident that self.a is borrowed.

如果没有将 self.a 标记为借用,您会遇到许多不安全的行为,例如可能的破坏性行为,而 Rust 旨在避免这些行为.

Without self.a being marked as borrowed, you run into plenty of unsafe behaviors, such as possible destructive behaviors, which Rust is designed to stay clear of.

这篇关于如何提供对同级结构的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆