[英]Cannot pass mutable reference to self directly
我目前正在链表上实现 Rust。 在任何事情之前,我已经阅读了 rust 文档学习 Rust With Entirely Too Many Linked Lists 。 但是我仍然在努力理解我在实现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
所以我不确定第二个实现有什么问题。
问题是打算直接可变的拥有变量必须可变绑定。
当您声明一个变量或一个 function 参数时,这可以统一为声明一个值到某个名称的绑定- 使用关键字let
或使用括号围绕 arguments 列表。 此绑定可以是可变的或不可变的,具体取决于mut
关键字的存在或不存在。
如果您将绑定声明为不可变,即省略mut
关键字,编译器会声明您不会获得对它的唯一引用(因此不会改变值,取模其中的任何UnsafeCell
)。 因此,如果您试图获取&mut
对它的引用,这是一个错误。
要修复错误,您可以可变地重新绑定变量,有效地丢弃先前的绑定(如果值不是Copy
),或者首先可变地绑定它 - 因为这是绑定的一部分,而不是变量声明的一部分,它可以在 function 声明中使用,也可以在let
语句中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.