【发布时间】:2022-10-23 02:54:33
【问题描述】:
我想创建一个TestStruct 的向量。 TestStruct 具有对另一个 TestStruct 实例的可选引用。没有TestStruct 将永远引用自己,也不会有预期用途的循环引用。多个others 可以引用同一个TestStruct。 TestStruct 实例不需要变异。
是否可以使用引用来表达这一点,还是我需要Rc 和Weak?
struct TestStruct<'a>
{
other: Option<&'a TestStruct<'a>>
}
fn testFn()
{
let mut events = vec![TestStruct{other: None}];
events.push(TestStruct{other: Some(&events[0])});
}
产量:
error[E0502]: cannot borrow `events` as mutable because it is also borrowed as immutable
--> src\test.rs:9:5
|
9 | events.push(TestStruct{other: Some(&events[0])});
| ^^^^^^^----^^^^^^^^^^^^^^^^^^^^^^^^^------^^^^^^
| | | |
| | | immutable borrow occurs here
| | immutable borrow later used by call
| mutable borrow occurs here
例如,我可以通过创建Box<TestStruct> 的向量来使其工作吗?或者对一个框在向量中的 TestStruct 的引用是否也会隐式借用该向量?
【问题讨论】:
标签: rust reference reference-counting