I've the following code. It it also available on the playground
use std::io;
use std::thread;
struct Foo<R: io::BufRead + Send + 'static> {
input: R,
}
impl<R> Foo<R>
where
R: io::BufRead + Send + 'static,
{
fn new(input: R) -> Self {
Foo { input: input }
}
fn start(&mut self) {
thread::spawn(move || self.read_input());
}
fn read_input(&mut self) {
loop {
let mut line = String::new();
if self.input.read_line(&mut line).expect("failed to read") == 0 {
return;
}
println!("{}", line)
}
}
}
fn main() {
let mut foo = Foo::new(io::Cursor::new("some text"));
foo.start();
}
In this snippet I create a trait object, io::Cursor
which implements io::BufRead
, in the main thread. I use this trait object to construct an instance of Foo
.
When I call Foo.start()
I start a new thread that operatos io::BufRead
trait object.
This code fails to compile with:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:17:23
|
17 | thread::spawn(move || self.read_input());
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 16:5...
--> src/main.rs:16:5
|
16 | / fn start(&mut self) {
17 | | thread::spawn(move || self.read_input());
18 | | }
| |_____^
= note: ...so that the types are compatible:
expected &mut Foo<R>
found &mut Foo<R>
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/main.rs:17:23: 17:48 self:&mut Foo<R>]` will meet its required lifetime bounds
--> src/main.rs:17:9
|
17 | thread::spawn(move || self.read_input());
| ^^^^^^^^^^^^^
error: aborting due to previous error
error: Could not compile `problem`.
Although I understand why it fails, I don't know how to fix it.
Can somebody help me with this? The lifetime of io::BufRead
can be static, I need at for the whole lifetime of my program.