Rust 试图维护自定义列表:一次不能多次借用 `self.array` 作为可变的

Rust trying to maintain self-defined list: cannot borrow `self.array` as mutable more than once at a time

我是 Rust 的新手,我试图在一个数组中维护 2 个链表,我的代码如下:

#[derive(Copy, Clone)]
struct Node {
    next: i32,
    prev: i32,
    val: i32
}

impl Node {

    pub fn new()->Self{
        Self{
            next: 0,
            val: 0,
            prev: 0
        }
    }
    pub fn get_prev(&self) -> i32{
        self.prev
    }

    pub fn get_next(&self) -> i32{
        self.next
    }

    pub fn set_prev(& mut self, idx: i32){
        self.prev = idx;
    }

    pub fn set_next(& mut self, idx: i32){
        self.next = idx;
    }

    pub fn get_val(&self)->i32{
        self.val
    }

    pub fn set_val(& mut self, v: i32){
        self.val = v;
    }
}

struct MyVec{
    red_start: i32,
    black_start: i32,
    data: [Node; 48]
}

impl MyVec{
    pub fn new()->Self{
        let mut ans = Self{
            red_start : -1,
            black_start: 0,
            data: [Node::new(); 48]
        };
        let len = ans.data.len();
        for i in 0..ans.data.len(){
            let n: & mut Node = & mut ans.data[i];
            n.set_prev(((i + len-1) % len) as i32);
            n.set_next(((i+1) % len) as i32);
        }
        ans
    }

    pub fn move_black_to_red(& mut self, idx: i32){
        let n: & mut Node = & mut self.data[idx as usize];
        let prev: & mut Node = & mut self.data[n.get_prev() as usize];
        let next: & mut Node = & mut self.data[n.get_next() as usize];
        prev.set_next(n.get_next());
        next.set_prev(n.get_prev());
        //other stuff...
    }
}

困难在move_black_to_red函数,我需要维护这个列表,所以我需要同时获取3个mut引用并更新它们。但是self最多只能借1个mut,怎么办?

Rust 不允许同时对同一个变量进行多个可变引用。解决这个问题的最简单方法是交错借用,并且不可变地借用 n,因为你永远不会改变它:

pub fn move_black_to_red(& mut self, idx: i32){
    let n: Node = self.data[idx as usize];

    let prev: & mut Node = & mut self.data[n.get_prev() as usize];
    prev.set_next(n.get_next());

    let next: & mut Node = & mut self.data[n.get_next() as usize];
    next.set_prev(n.get_prev());

    //other stuff...
}