【问题标题】:Rust LinkedList second mutable borrow while moving first item to the endRust LinkedList 第二个可变借用,同时将第一项移动到末尾
【发布时间】:2021-04-25 12:37:58
【问题描述】:

美好的一天! 我试图将第一项移动到链表中的末尾。 我有一个这样的链表:

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);

那就好了。

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

【问题讨论】:

    标签: rust borrow-checker


    【解决方案1】:

    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);
    

    【讨论】:

    • 谢谢!但是对于第一个,为什么它不会在list.pop_front().unwrap() 返回后删除可变引用?
    • Afaik,编译器无法推断。它一次一行地静态分析代码。
    猜你喜欢
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多