繁体   English   中英

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

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

再会。 我试图将第一项移动到链表中的末尾:我有一个这样的链表:

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

如果我像这样移动项目:

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

Rust 会抛出“第二个可变借用发生”错误。

但是如果在另一行代码中获取第一项:

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

然后就好了。

为什么这两段代码的行为不同? 我完全不明白。。

push_backpop_front都是保留对列表的可变引用的方法,因此您不能这样做:

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

以您指出的另一种方式进行操作,因为您将可变引用放在第一行的末尾:

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