I'm trying to move struct, that has a member as a reference, to another thread and get the compile time error '... borrowed does not live long enough'.
use std::thread;
#[derive(Debug, Clone)]
struct Video {
id: u32,
name: String
}
struct VideoService<'a> {
list: &'a Vec<Video>
}
impl VideoService<'_> {
fn new(videos: &Vec<Video>) -> VideoService {
VideoService { list: videos }
}
fn get_by_id(&self, id: u32) -> Option<Video> {
self.list.iter().filter(|video| {
video.id == id
}).collect::<Vec<_>>().get(0).cloned().cloned()
}
}
pub fn run_video_service_v2() {
let videos = vec![
Video { id: 1, name: "AAA".to_string() },
Video { id: 2, name: "BBB".to_string() }
];
let video_service = VideoService::new(&videos);
let handle = thread::spawn(move || {
println!("{:?}", video_service.get_by_id(1));
});
handle.join();
}
--> src/video_service_v2.rs:30:43
|
30 | let video_service = VideoService::new(&videos);
| ------------------^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires thatvideos
is borrowed for'static
...
36 | }
| -videos
dropped here while still borrowed
I can fix it by moving videos variable into VideoService. But for learning rust I 'd like to send videos variable as reference.
I'd like to understand why I get this error. Is it because thread has lifetime beyond the function run_video_service_v2()?
If possible, please also give me the link to the The Rust Programming Language - The Rust Programming Language the section that explain about this so that I can get more understanding.