2

以下代码无法编译:

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

4

0 回答 0