到目前为止,我认为这move |...| {...}会将变量移动到闭包内,闭包只会实现FnOnce,因为你只能移动变量一次.然而,令我惊讶的是,我发现此代码有效:
extern crate futures;
use futures::stream;
use futures::stream::{Stream, StreamExt};
use std::rc::Rc;
#[derive(Debug)]
struct Foo(i32);
fn bar(r: Rc<Foo>) -> Box<Stream<Item = (), Error = ()> + 'static> {
Box::new(stream::repeat::<_, ()>(()).map(move |_| {
println!("{:?}", r);
}))
}
fn main() {
let r = Rc::new(Foo(0));
let _ = bar(r);
}
Run Code Online (Sandbox Code Playgroud)
尽管map有这个签名:
fn map<U, F>(self, f: F) -> Map<Self, F>
where
F: FnMut(Self::Item) -> U,
Run Code Online (Sandbox Code Playgroud)
令我惊讶的FnMut是,在使用move关键字时创建了一个闭包,它甚至具有'static生命周期.我在哪里可以找到一些细节move?或者它是如何实际工作的?
rust ×1