[英]Rust custom link list pop_back implementation
I'm new to rust and try to understand &mut ref variables and mutability.我是 rust 的新手,并尝试了解 &mut ref 变量和可变性。 I started creating a simple link list with pop_back function.
我开始使用 pop_back function 创建一个简单的链接列表。
pub fn pop_back(&mut self) -> Option<T> {
let mut head = &mut self.head;
while let Some(v) = head {
if v.next.is_none() {
break;
}
head = &mut v.next;
}
head.take().map(|node| node.data)
}
but can't make it to work.但不能让它工作。 error is
cannot borrow *head as mutable more than once at a time
.错误是
cannot borrow *head as mutable more than once at a time
。 How can I tell rust that I want to only change the reference in my loop not the value?如何告诉 rust 我只想更改循环中的引用而不是值? I don't want to add another tail variable to my list so without changing structure how can I make this work?
我不想在我的列表中添加另一个尾变量,所以在不改变结构的情况下我怎样才能使它工作?
this is the struct definition这是结构定义
pub struct Node<T> {
data: T,
next: Option<Box<Node<T>>>
}
pub struct SimpleLinkedList<T> {
head: Option<Box<Node<T>>>,
}
This is a known limitation of the borrow checker.这是借用检查器的已知限制。 The next-gen Polonius will solve this.
下一代Polonius将解决这个问题。
In the meantime, the solution (without unsafe
) is to repeat the calculation.同时,解决方案(没有
unsafe
)是重复计算。 In your case, this means some unwrap()
s:在您的情况下,这意味着一些
unwrap()
s:
pub fn pop_back(&mut self) -> Option<T> {
let mut head = &mut self.head;
while head.is_some() {
if head.as_mut().unwrap().next.is_none() {
break;
}
head = &mut head.as_mut().unwrap().next;
}
head.take().map(|node| node.data)
}
See also:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.