目前,我正在研究一个小应用程序来模拟(多链)摆。为了保存它们,我决定使用std :: collections :: LinkedList。
显示它们并静态地移动它们不是问题,但是为了计算实际运动,我需要知道父子摆的一些值。
我真的不需要对它们的可变引用,但是链表API并没有让我采用一成不变的方法。但是我猜想这仍然不会改变编译器的主意,因为它仍然是可变的并且有些不可变的借用。
我的代码如下:
let mut cursor = /* some linked list with 0 or more elements */.cursor_front_mut();
// the first element gets a phantom parent, that has no effect on the calculation
let mut first = Pendulum::zero_center();
// same with the last element. But we don't know the position of this phantom yet.
let mut last;
while let Some(current) = cursor.current() { // << first mutable borrow occurs here
{
// new scope, so I don't mutate the cursor while holding mutable references
// to the surrounding elements
// (I don't really need the next two borrows to be mutable)
let parent = match cursor.peek_prev() { // << second mutable borrow occurs here
Some(parent) => parent,
None => &mut first
};
let child = match cursor.peek_next() { // third mutable borrow occurs here
Some(child) => child,
None => {
last = Pendulum::zero(current.bottom_pos); // << bottom_pos is of type Copy
&mut last
}
};
// update the current pendulum
// update does take a immutable reference of parent and child
// since it only needs to read some values of them
current.update(parent, child);
}
cursor.move_next();
}
如果将这段代码包装在不安全的{}中,编译器将不在乎,并不断告诉我我有多个可变借项+不必要的unsafe
块。
如果有人可以帮助我,那将太可怕了!如果在这里使用LinkedList完全是垃圾,并且有更好的方法请告诉我!
非常感谢!
通常,可变引用要求对其所指向的对象具有独占访问权,并且不安全的块对此没有影响。原始指针没有此要求,因此编写违反这些要求的代码将必须使用原始指针。
用不安全的Rust来实现链表将超出SO答案的范围,但是我建议使用Learning Rust with too many Linked Lists作为解决此问题的方法的资源。
有时使用在向量中使用索引来构建链接列表是一种很好的替代方法,它可以解决Rust对其引用提出的许多要求上的任何问题。