rust - 为什么循环内的一些 while-let 分配无法编译,“不能一次多次借用可变”?
问题描述
struct Foo(Option<Box<Foo>>);
fn func(mut foo: Foo) {
let mut bar = &mut foo;
loop {
// while let Some(next) = bar.0.as_mut() { // version-1
// while let Some(next) = &mut bar.0 { // version-2
while let Some(ref mut next) = bar.0 { // version-3
bar = next.as_mut();
}
}
}
上面的代码中,只有version-3可以编译成功。我想知道这三个版本之间的区别以及为什么只有版本 3 是有效的。
请注意,在版本 3 中,bar.0
似乎没有移动到左侧模式。一个简单的试验:
let mut a = Foo(Some(Box::new(Foo(None))));
if let Some(ref mut _b) = a.0 {
// Foo does not implement the `Copy` trait
println!("Go into if-let");
}
let b = a; // Moving occurs here, so `a.0` is not moved
版本 1 的错误消息:
error[E0499]: cannot borrow `bar.0` as mutable more than once at a time
--> src/lib.rs:6:32
|
6 | while let Some(next) = bar.0.as_mut() { // version-1
| ^^^^^ mutable borrow starts here in previous iteration of loop
版本 2 的错误消息:
error[E0499]: cannot borrow `bar.0` as mutable more than once at a time
--> src/lib.rs:7:32
|
7 | while let Some(next) = &mut bar.0 { // version-2
| ^^^^^^^^^^ mutable borrow starts here in previous iteration of loop
解决方案
推荐阅读
- dart - 如何从异步函数返回惰性 Iterable
- android - Flutter 错误 - FileSystemException:创建失败,路径 = 'storage/emulated/0/myDir'(操作系统错误:不允许操作,errno = 1)
- google-sheets - 谷歌表:在查询输出中插入空白列
- asp.net-mvc - 渲染局部视图 ASP MVC
- scom - SCOM - Runas 帐户 WriteAction 不起作用
- swift - 如何在 UICollectionView 创建两个按水平排列的部分
- javascript - 将函数变量暴露给外部并在函数调用期间访问它们
- excel - 如何使用表格公式(或谷歌应用程序脚本)查找日期范围的多少天属于另一个日期范围?
- json - 根据来自 URL "[FLUTTER] " 的 JSON 值进行重定向
- c++11 - static_assert 抛出错误“静态断言的非常量条件”