Threads and lifetime problem

I have a situation like in the following minimal example

extern crate threadpool;
use std::env;
use std::sync::Mutex;
use threadpool::ThreadPool;


pub struct Blabla {
    pool: Mutex<ThreadPool>,
}

impl Blabla {
    pub fn new(num_threads: usize) -> Blabla {
        let pool = Mutex::new(ThreadPool::new(num_threads));
        Blabla{ pool }
    }


    pub fn check_file(&self, fname: &str) {
        let s = String::from(fname);
        let pool = self.pool.lock().unwrap();
        pool.execute(move ||{
            self.check_file_inner(s); 
        });
    }

    fn check_file_inner(&self, fname: String) {
        println!("Do something with {}", fname);
    }
}


fn main() {
    let args: Vec<String> = env::args().skip(1).collect();
    let bla = Blabla::new(5);
    for fname in args {
        bla.check_file(&fname);
    }
}

The compiler gives me

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:22:22
   |
22 |           pool.execute(move ||{
   |  ______________________^
23 | |             self.check_file_inner(s); 
24 | |         });
   | |_________^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 19:5...
  --> src/main.rs:19:5
   |
19 | /     pub fn check_file(&self, fname: &str) {
20 | |         let s = String::from(fname);
21 | |         let pool = self.pool.lock().unwrap();
22 | |         pool.execute(move ||{
23 | |             self.check_file_inner(s); 
24 | |         });
25 | |     }
   | |_____^
   = note: ...so that the types are compatible:
           expected &Blabla
              found &Blabla
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/main.rs:22:22: 24:10 self:&Blabla, s:std::string::String]` will meet its required lifetime bounds
  --> src/main.rs:22:14
   |
22 |         pool.execute(move ||{
   |              ^^^^^^^

I have to admit I have no idea how to solve this. Any help appreciated.

The main problem is that you are trying to move self inside the lambda at lines 22-23.

If you change line 23 to

Blabla::check_file_inner(s);

and line 26 to

fn check_file_inner(fname: String)

then it works flawlessly, because you are only moving the string.

If you need a reference of Blabla passed to check_file_inner, then you probably need to refactory the code a bit.

Thanks. Your are right. If I have check_file_inner() outside of Blabla then things work fine.

In my situation this is ok to do.

Thanks again.