gpt4 book ai didi

scope - "does not live long enough"创建可在线程间传递的引用二叉树时

转载 作者:行者123 更新时间:2023-11-29 08:25:45 26 4
gpt4 key购买 nike

<分区>

我正在尝试编写一个二叉树,它可以在线程之间传递,而不必每次都复制。我很难理解如何使用 Rust 对生命周期的限制来做到这一点。

use std::thread::spawn;

#[derive(Debug)]
struct Node<'a> {
left: &'a i32,
right: &'a i32,
}

fn main() {
let l = 3;
let r = 4;
let n = Node {
left: &l,
right: &r,
};

spawn(|| {
println!("{:?}", n);
});
}
error[E0597]: `l` does not live long enough
--> src/main.rs:13:15
|
13 | left: &l,
| ^^ borrowed value does not live long enough
...
17 | / spawn(|| {
18 | | println!("{:?}", n);
19 | | });
| |______- argument requires that `l` is borrowed for `'static`
20 | }
| - `l` dropped here while still borrowed

error[E0597]: `r` does not live long enough
--> src/main.rs:14:16
|
14 | right: &r,
| ^^ borrowed value does not live long enough
...
17 | / spawn(|| {
18 | | println!("{:?}", n);
19 | | });
| |______- argument requires that `r` is borrowed for `'static`
20 | }
| - `r` dropped here while still borrowed

error[E0373]: closure may outlive the current function, but it borrows `n`, which is owned by the current function
--> src/main.rs:17:11
|
17 | spawn(|| {
| ^^ may outlive borrowed value `n`
18 | println!("{:?}", n);
| - `n` is borrowed here
|
note: function requires argument type to outlive `'static`
--> src/main.rs:17:5
|
17 | / spawn(|| {
18 | | println!("{:?}", n);
19 | | });
| |______^
help: to force the closure to take ownership of `n` (and any other referenced variables), use the `move` keyword
|
17 | spawn(move || {
| ^^^^^^^

我理解为什么它会认为他们活得不够长,但我应该如何重组它才能让他们活得足够长?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com