在以下代码段中:
let read_pool = ReadPool::new(
"readpool",
&Config::default_for_test(),
|| || Context {}
);
四条垂直线|| ||
是什么?
答案 0 :(得分:10)
||
代表不带参数的lambda。
fn main() {
let a = || println!("hello");
let b = || { println!("world") };
a(); // hello
b(); // world
}
两个在一起是一个lambda,返回另一个lambda:
fn main() {
let a = || || println!("hello world");
let c = a();
c(); // hello world
}
答案 1 :(得分:3)
在Rust中,||
引入了一个lambda(一个未命名的函数)。
lambda的参数在两者之间指定:
|a, b| a + b
:一个带有2个自变量a
和b
并返回其总和的lambda,|| println!("Hello, World")
:一个不带参数的lambda并显示“ Hello,World!”。由于lambda的主体只是一个表达式,因此它可以是另一个lambda:
|| || println!("Hello, World")
:不带参数的lambda,不带参数的lambda,返回“ Hello,World!”。因此,|| || Context {}
很简单:
|| Context {}
的lambda,Context
实例的lambda。答案 2 :(得分:3)
根据that function's source,此模式称为闭包生成器:
// Rust不支持复制闭包(RFC 2132),因此我们需要一个 关闭器生成器。
// TODO:一旦RFC 2132被使用,则使用单个闭包 已实施。
相关的代码片段显示此参数是a function or closure返回另一个参数,两者都没有参数(|| || Context {}
坚持使用):
// src/server/readpool/mod.rs
pub fn new<F, CF>(name_prefix: &str,
config: &Config,
context_factory_builder: F // this is the argument in question
) -> Self where
F: futurepool::Factory<CF>,
CF: futurepool::Factory<T>
// src/util/futurepool.rs:
pub trait Factory<T> {
fn build(&self) -> T;
}
impl<T, F> Factory<T> for F
where F: Fn() -> T // a function taking no arguments
{
fn build(&self) -> T {
self()
}
}