简体   繁体   English

Rust LinkedList 第二个可变借用,同时将第一项移动到末尾

[英]Rust LinkedList second mutable borrow while moving first item to the end

Good day.再会。 I was trying to move the first item to the end in a linked list: I have a linked list like this:我试图将第一项移动到链表中的末尾:我有一个这样的链表:

let mut list = LinkedList::new();
list.push_back('a');
list.push_back('b');
list.push_back('c');

If I move item like this:如果我像这样移动项目:

list.push_back(list.pop_front().unwrap());

Rust would throw an "second mutable borrow occurs" error. Rust 会抛出“第二个可变借用发生”错误。

But If a get the first item at another line of code:但是如果在另一行代码中获取第一项:

let str = list.pop_front().unwrap();
list.push_back(str);

Then it's fine.然后就好了。

Why these two pieces of code behave differently?为什么这两段代码的行为不同? I totally don't understand..我完全不明白。。

Both push_back and pop_front are methods that keep a mutable reference to list, so you can't do this: push_backpop_front都是保留对列表的可变引用的方法,因此您不能这样做:

list.push_back(list.pop_front().unwrap());

Doing it the other way that you pointed out works because you drop the mutable reference at the end of the first line:以您指出的另一种方式进行操作,因为您将可变引用放在第一行的末尾:

let str = list.pop_front().unwrap(); // mutable reference dropped here, so it's fine to have another mutable reference afterwards
list.push_back(str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM