【发布时间】:2018-05-08 15:56:33
【问题描述】:
我正在尝试在 Rust 中实现一个链表,但我在理解这两个函数之间的区别时遇到了一些麻烦:
enum List<T> {
Nil,
Cons(T, Box<List<T>>)
}
fn foo<T>(list: &mut Box<List<T>>) {
match **list {
List::Nil => return,
List::Cons(ref mut head, ref mut tail) => {
// ...
}
}
}
fn bar<T>(list: &mut List<T>) {
match *list {
List::Nil => return,
List::Cons(ref mut head, ref mut tail) => {
// ...
}
}
}
foo编译失败,报错:
error[E0499]: cannot borrow `list` (via `list.1`) as mutable more than once at a time
--> src/main.rs:66:34
|
66 | List::Cons(ref mut head, ref mut rest) => {
| ------------ ^^^^^^^^^^^^ second mutable borrow occurs here (via `list.1`)
| |
| first mutable borrow occurs here (via `list.0`)
...
69 | }
| - first borrow ends here
但是,bar 可以完美编译和运行。为什么bar 有效,而foo 无效?我正在使用 Rust 1.25 版。
【问题讨论】:
标签: rust