我如何处理/规避“无法分配给......后面的&参考"在锈? [英] How do I handle/circumvent "Cannot assign to ... which is behind a & reference" in Rust?

查看:28
本文介绍了我如何处理/规避“无法分配给......后面的&参考"在锈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会实现一个简单的链表.这是我迄今为止的(工作)代码:

I'd implementing a simple linked list. This is the (working) code I had so far:

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,
        };
    }
}

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

Next on the list is a method to append to the list; this is what I came up with:

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

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

I vaguely get the problem; you cannot mutate an immutable reference. But making the references mutable does seem to make the errors even worse.

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

How does one handle these kinds of errors? Is there a simple quick-fix, or do you structure your code completely different in Rust?

推荐答案

您的代码几乎可以工作了.如果你可变绑定:

Your code almost worked. It will if you 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 中有关可变性、类型和绑定的问题.

FYI, the answer to this recent question is very good at clarifying the matter about mutability, type and binding in Rust.

这篇关于我如何处理/规避“无法分配给......后面的&amp;参考"在锈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆