无法将可变引用直接传递给自己

问题描述 投票:0回答:1

我目前正在研究链表上的Rust实现。在开始之前,我已经阅读了Learning Rust With Entirely Too Many Linked Lists上的rust文档。但是我仍然在努力理解实现into()特性时遇到的错误。

这是我实现它的方式(现在似乎可以运行:):

impl<T> Into<Vec<T>> for SimpleLinkedList<T> {
    fn into(self) -> Vec<T> {
        let mut res = Vec::new();
        let mut mutable_to_self = self;

        fn into_rec<T>(list: &mut SimpleLinkedList<T>, v: &mut Vec<T>) {
            if let Some(x) = list.pop() {
                into_rec(list, v);
                v.push(x);
            }
        }

        into_rec(&mut mutable_to_self, &mut res);
        res

我对此感到困惑,需要mutable_to_self。首先,我尝试摆脱此变量,只是将&mut self直接传递给into_rec()(对我来说,这是完全一样的)。但是,当我这样做时,我得到:

error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable
  --> src/lib.rs:93:18
   |
82 |     fn into(self) -> Vec<T> {
   |             ---- help: consider changing this to be mutable: `mut self`
...
93 |         into_rec(&mut self, &mut res);
   |                  ^^^^^^^^^ cannot borrow as mutable

error: aborting due to previous error

For more information about this error, try `rustc --explain E0596`.
error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable
  --> src/lib.rs:93:18
   |
82 |     fn into(self) -> Vec<T> {
   |             ---- help: consider changing this to be mutable: `mut self`
...
93 |         into_rec(&mut self, &mut res);
   |                  ^^^^^^^^^ cannot borrow as mutable

所以我不确定第二个实现有什么问题。

linked-list rust mutability
1个回答
0
投票

问题是,旨在直接可变的自有变量必须可变绑定。

声明变量或函数参数时,可以统一为将值声明为值的[[binding-使用关键字let或参数列表中的括号。此绑定可以是可变的,也可以是不可变的,具体取决于是否存在mut关键字。

如果将绑定声明为不可变的,即省略mut关键字,则编译器会声明您不会获取对其的唯一引用(因此,不会对该值进行变异,对其中的任何UnsafeCell取模) )。因此,如果您尝试获取对它的&mut引用,这是一个错误。

要纠正错误,您可以可变地重新绑定变量,有效地放弃先前的绑定(如果值不是Copy),或者可以可变地首先绑定它-因为这是绑定的一部分,而不是变量声明,可以在函数声明以及let语句中使用相同的变量。]​​>

© www.soinside.com 2019 - 2024. All rights reserved.