考虑以下代码(Playground 版本):
use std::cell::Cell;
struct Foo(u32);
#[derive(Clone, Copy)]
struct FooRef<'a>(&'a Foo);
// the body of these functions don't matter
fn testa<'a>(x: &FooRef<'a>, y: &'a Foo) { x; }
fn testa_mut<'a>(x: &mut FooRef<'a>, y: &'a Foo) { *x = FooRef(y); }
fn testb<'a>(x: &Cell<FooRef<'a>>, y: &'a Foo) { x.set(FooRef(y)); }
fn main() {
let u1 = Foo(3);
let u2 = Foo(5);
let mut a = FooRef(&u1);
let b = Cell::new(FooRef(&u1));
// try one of the following 3 statements
testa(&a, &u2); // allow move at (1)
testa_mut(&mut a, &u2); // deny move -- fine!
testb(&b, &u2); // deny move -- but how does rustc know?
u2; // (1) move out
// ... do something with a or b
}
我很好奇如何rustc
知道它Cell
具有内部可变性并且可能会保留对另一个论点的引用。
如果我从头开始创建另一个数据结构,类似于Cell
它也具有内部可变性,我该如何判断rustc
?