>, } impl LinkedList { pu-6ren">
gpt4 book ai didi

rust - 如何在 Rust 中处理/规避 "Cannot assign to ... which is behind a & reference"?

转载 作者:行者123 更新时间:2023-12-03 11:27:50 26 4
gpt4 key购买 nike

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

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

仅供引用, the answer to this recent question非常擅长阐明 Rust 中关于可变性、类型和绑定(bind)的问题。

关于rust - 如何在 Rust 中处理/规避 "Cannot assign to ... which is behind a & reference"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59729961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com