Extend lifetime of a variable for thread

后端 未结 1 979
暖寄归人
暖寄归人 2020-12-21 16:17

I am reading a string from a file, splitting it by lines into a vector and then I want to do something with the extracted lines in separate threads. Like this:



        
相关标签:
1条回答
  • 2020-12-21 16:28

    The problem, fundamentally, is that line is a borrowed slice into s. There's really nothing you can do here, since there's no way to guarantee that each line will not outlive s itself.

    Also, just to be clear: there is absolutely no way in Rust to "extend the lifetime of a variable". It simply cannot be done.

    The simplest way around this is to go from line being borrowed to owned. Like so:

    use std::thread;
    fn main() {
        let mut s: String = "One\nTwo\nThree\n".into();
        let k : Vec<String> = s.split("\n").map(|s| s.into()).collect();
        for line in k {
            thread::spawn(move || {
                println!("nL: {:?}", line);
            });
        }
    }
    

    The .map(|s| s.into()) converts from &str to String. Since a String owns its contents, it can be safely moved into each thread's closure, and will live independently of the thread that created it.

    Note: you could do this in nightly Rust using the new scoped thread API, but that is still unstable.

    0 讨论(0)
提交回复
热议问题