目前,我正在开发一个小应用程序来模拟(多链)钟摆。为了保存它们,我决定使用 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 {} 中,编译器不会在意并一直告诉我我有多个可变借用 + 一个不必要的unsafe
块。
如果有人可以帮助我,那就太棒了!
如果在这里使用 LinkedList 完全是垃圾,并且有更好的方法,请告诉我!
提前谢谢了!