Some borrow value error about function params

use std::thread;

pub struct DownloadParams<'a> {
    pub save_dir: &'a str,
    pub download_url: &'a str,
    pub app_name: &'a str,
}
fn test(params: &[DownloadParams<'_>]) {
    let mut handles = vec![];
    for p in params.iter() {
        let DownloadParams {
            download_url,
            app_name,
            save_dir,
        } = p.clone();
        let builder = thread::Builder::new().name(app_name.to_string());
        let handle = builder
            .spawn(move || {
                println!("download_url is {download_url}");
            })
            .unwrap();
        handles.push(handle);
    }
}

playground link

the error was like

I've copy the param by p.clone(), why there's borrow error?

download_url is still a reference. Cloning an immutable/shared reference returns just another reference to the same data, as &T implements Copy:

use std::thread;


pub struct DownloadParams<'a> {
    pub save_dir: &'a str,
    pub download_url: &'a str,
    pub app_name: &'a str,
}
fn test(params: &[DownloadParams<'_>]) {
    let mut handles = vec![];
    for p in params.iter() {
        let DownloadParams {
            download_url,
            app_name,
            save_dir,
        } = p.clone();
        
        // create an owned value
        let download_url = download_url.to_string();
        
        let builder = thread::Builder::new().name(app_name.to_string());
        let handle = builder
            .spawn(move || {
                println!("download_url is {download_url}");
            })
            .unwrap();
        handles.push(handle);
    }
}

fn main() {
}

Playground.

ok I see, thanks for pointing out

Note that if you want to immediately join the threads you are spawning in test, you can use std::thread::scope. This'd allow you to pass non-'static data to the closures executed by your threads.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.