gpt4 book ai didi

rust - 捕获的变量不会超过封闭的闭包

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

<分区>

我在 Rust 中有一个线程操作,它需要使用一个变量作为参数传递给线程在其中生成的函数,但是我看到以下编译时错误:

   Compiling Test v0.0.1 (file:///Users/clarkj84/Desktop/RustTest)
main.rs:9:22: 9:35 error: captured variable `test` does not outlive the enclosing closure
main.rs:9 let handle = thread::spawn(move || {
^~~~~~~~~~~~~
main.rs:7:20: 16:2 note: captured variable is valid for the anonymous lifetime #1 defined on the block at 7:19
main.rs:7 fn test(test: &str){
main.rs:8 for _x in 0..2 {
main.rs:9 let handle = thread::spawn(move || {
main.rs:10 for _y in 0..2 {
main.rs:11 println!("{}", test);
main.rs:12 }
...
note: closure is valid for the static lifetime
error: aborting due to previous error
Could not compile `Test`.

To learn more, run the command again with --verbose.

这是我的代码实现:

use std::thread;

fn main() {
test("test");
}

fn test(test: &str){
for _x in 0..2 {
let handle = thread::spawn(move || {
for _y in 0..2 {
println!("{}", test);
}
});
}
}

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