My guess (based on your earlier post) is that you have something like this:
let handle = /* ... */;
incoming.for_each(move |(addr, req)| {
let duration = something;
blahblah.and_then(move |o| {
print!("{}", str::from_utf8(&o.stdout).unwrap());
Timeout::new(Duration::from_secs(duration), &handle).unwrap()
})
})
What the compiler sees is more like (pseudocode):
let handle = /* ... */;
incoming.for_each(__Closure1 { __h1: handle })
struct __Closure1 { __h1: Handle }
impl FnMut for __Closure1 {
fn call_mut(&mut self, (addr, req)) {
let duration = something;
blahblah.and_then(__Closure2 { __h2: self.__h1, __d1: duration })
// can't move self.__h1! ^^^^^^^^^
// because self is &mut!
}
}
struct __Closure2 { __h2: Handle, __d1: Duration }
impl FnOnce for __Closure2 {
fn call_once(self, o) {
print!("{}", str::from_utf8(&o.stdout).unwrap());
Timeout::new(Duration::from_secs(self.__d1), &self.__h2).unwrap()
}
}
The handle gets moved into the environment (self) of __Closure1. Inside __Closure1, you are asking for the handle to be moved again into __Closure2, but because __Closure1 is FnMut (i.e. it could be called multiple times), you only get &mut access to the environment, so you aren’t allowed to move things out of the environment as that would invalidate the environment for future invocations. Conceptually it’s the same reason you aren’t allowed to write code such as:
let handle: Handle = /* ... */;
loop {
use_handle(handle); // oops, handle is gone now
// what will happen on the next iteration!?
}
The trick is to make a clone of handle within __Closure1 (which I think you’ve already discovered). This clone will be called on each invocation of __Closure1, bypassing the problem.