以下代码无法编译:
use std::thread;
#[derive(Debug)]
struct Contained {
a: u8
}
#[derive(Debug)]
struct Wrapper<'a> {
b: &'a Contained,
}
fn main() {
println!("Hello, world!");
let c = Contained { a: 42 };
let w = Wrapper { b: &c };
println!("C: {:?}", c);
println!("W: {:?}", w);
let handle = thread::spawn(move || {
println!("C in thread: {:?}", c);
});
handle.join().unwrap();
}
错误讯息:
src/main.rs:24:39: 24:40 error: cannot move `c` into closure because it is borrowed [E0504]
src/main.rs:24 println!("C in thread: {:?}", c);
^
<std macros>:2:25: 2:56 note: in this expansion of format_args!
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
src/main.rs:24:9: 24:42 note: in this expansion of println! (defined in <std macros>)
src/main.rs:18:27: 18:28 note: borrow of `c` occurs here
src/main.rs:18 let w = Wrapper { b: &c };
^
借阅检查员显然是对的。解决此问题的方法是使用显式范围,以便删除包装器,释放借来的包含对象。
let c = Contained { a: 42 };
{
let w = Wrapper { b: &c };
println!("C: {:?}", c);
println!("W: {:?}", w);
}
let handle = thread::spawn(move || {
println!("C in thread: {:?}", c);
});
这可以正确编译。
使对象超出范围的另一种方法是使用std::mem::drop
函数。在这种情况下,它不起作用:
let c = Contained { a: 42 };
let w = Wrapper { b: &c };
println!("C: {:?}", c);
println!("W: {:?}", w);
drop(w);
let handle = thread::spawn(move || {
println!("C in thread: {:?}", c);
});
借用检查程序使用与之前相同的错误消息进行投诉。
为什么drop(w)
没有释放借来的c
?