How can I provide a reference to a struct that is

2020-02-14 07:54发布

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 },
    }
}

标签: rust
2条回答
男人必须洒脱
2楼-- · 2020-02-14 08:00

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

  1. have a syntax that unambiguously allows referring to a sibling
  2. make it so that borrowing rules can still be verified

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.

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.

查看更多
叛逆
3楼-- · 2020-02-14 08:21

This simply cannot be represented in safe Rust code.

In cases like this, you may need to resort to dynamic borrowing with things like RefCell.

查看更多
登录 后发表回答