我如何在 Rust 中 handle/circumvent "Cannot assign to ... which is behind a & reference"?

How do I handle/circumvent "Cannot assign to ... which is behind a & reference" in Rust?

我要实现一个简单的链表。这是我到目前为止的(工作)代码:

pub struct LinkedList<T> {
    start: Option<Box<Link<T>>>,
}

impl<T> LinkedList<T> {
    pub fn new() -> LinkedList<T> {
        return LinkedList { start: None };
    }
}

struct Link<T> {
    value: Box<T>,
    next: Option<Box<Link<T>>>,
}

impl<T> Link<T> {
    fn new_end(value: T) -> Link<T> {
        return Link::new(value, None);
    }

    fn new(value: T, next: Option<Box<Link<T>>>) -> Link<T> {
        return Link {
            value: Box::new(value),
            next,
        };
    }
}

列表的下一个是附加到列表的方法;这是我想出的:

pub fn append(&mut self, element: T) {
    // Create the link to append
    let new_link = Some(Box::new(Link::new_end(element)));

    // Find the last element of the list. None, if the list is empty
    let mut last = &self.start;
    while let Some(link) = last {
        last = &link.next;
    }

    // Insert the new link at the correct position
    match last {
        None => self.start = new_link,
        Some(last) => last.next = new_link, // This fails
    }
}

准确的编译器错误是

error[E0594]: cannot assign to `last.next` which is behind a `&` reference

我隐约明白了问题;你不能改变一个不可变的引用。但是使引用可变似乎会使错误变得更糟。

如何处理这些类型的错误?有没有简单的快速修复方法,或者您在 Rust 中构建完全不同的代码?

您的代码几乎可以正常工作。如果你 bind mutably:

impl<T> LinkedList<T> {
    pub fn append(&mut self, element: T) {
        // Create the link to append
        let new_link = Some(Box::new(Link::new_end(element)));

        // Find the last element of the list. None, if the list is empty
        let mut last = &mut self.start;
        while let Some(link) = last {
            last = &mut link.next;
        }

        // Insert the new link at the correct position
        match last {
            None => self.start = new_link,
            Some(ref mut last) => last.next = new_link,
        }
    }
}

仅供参考, 非常擅长阐明 Rust 中有关可变性、类型和绑定的问题。