fnmain(){letmutv=vec![1,2,3];letfoo=&mutv;letbar=&mut*foo;// 重借用, foo 临时移动到 bar, bar 生命周期结束后会归回。
//let bar = foo; // 不是重借用, 是 move, 不会自动归回。
//let bar: &mut Vec<i32> = foo; // 编译器知道类型会发生重借用
//let bar: &mut _ = foo; // 不指明类型也会发生重借用
//foo.push(3); // error: second mutable borrow occurs here. 重借用也不能发生两次可变借用。
bar.push(4);foo.push(5);// 重借用不是 move, bar 的生命周期结束后, 会归回, 而 move 不会。
}
For example:
1
2
3
4
5
6
7
8
9
10
11
12
fnbar<T>(_a: T,_b: T){}fnmain(){letmuti=42;letmutj=43;letx=&muti;lety=&mutj;bar(x,y);// Moves x, but reborrows y.
// 首先是推导模板参数, 所以编译器不知道第一个参数的类型, 推导出类型后, 第二个参数类型知道了。
let_z=x;// error[E0382]: use of moved value: `x`
let_t=y;// Works fine.
}
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
structX;traitFoo: Sized{fnfoo(self){}// let self = <param>
}implFoofor&mutX{}fnmain(){letx: &mutX=&mutX;x.foo();x.foo();// Reborrows x
letx: &mutX=&mutX;Foo::foo(x);Foo::foo(x);// Doesn't reborrow x, fails to compile
}