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

时间:2015-06-23 11:20:53

标签: rust

我在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);
            }
        });
    }    
}

1 个答案:

答案 0 :(得分:2)

结帐@Shepmaster's answer以获取解释。根据您的使用情况,您的问题有两种解决方案。

如果您的用例只是字符串文字(类型为&'static str)而不是在程序执行期间创建的任意字符串,则可以将函数的签名修改为

fn test(test: &'static str)

这将允许您将任何字符串文字传递给此函数并将字符串文字移动到另一个线程。

另一方面,如果要创建新的字符串,例如从程序参数或环境变量中获取它们,然后您可以为每个线程创建一个String对象并传递它。

use std::thread;
use std::env;

fn main() {
    test("test");
    test(std::env::var("HOME").unwrap()); // pass the current home-directory
}

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