我无法理解为什么在借款人范围结束后仍然借用可变借入变量。它看起来就像是要使用的特质有关,但我不明白为什么:借款人范围结束时无法借入变量
fn main() {
let mut a = 10;
test::<FooS>(&mut a);
println!("out {:?}", a)
}
trait Foo<'a> {
fn new(data: &'a mut u32) -> Self;
fn apply(&mut self);
}
struct FooS<'a> {
data: &'a mut u32,
}
impl<'a> Foo<'a> for FooS<'a> {
fn new(data: &'a mut u32) -> Self {
FooS { data: data }
}
fn apply(&mut self) {
*self.data += 10;
}
}
fn test<'a, F>(data: &'a mut u32)
where F: Foo<'a>
{
{
// let mut foo = FooS {data: data}; // This works fine
let mut foo: F = Foo::new(data);
foo.apply();
} // foo scope ends here
println!("{:?}", data); // error
} // but borrowed till here
error: cannot borrow `data` as immutable because `*data` is also borrowed as mutable [--explain E0502]
--> <anon>:34:22
31 |> let mut foo: F = Foo::new(data);
|> ---- mutable borrow occurs here
...
34 |> println!("{:?}", data); // error
|> ^^^^ immutable borrow occurs here
35 |> } // but borrowed till here
|> - mutable borrow ends here
https://play.rust-lang.org/?gist=dabe17d66a14e72c2ca67e064ca26601&version=nightly&backtrace=0的作品。所以...... – Jacob
不过,这似乎是一个错误。 – JDemler