【发布时间】:2020-11-10 20:06:00
【问题描述】:
我正在使用 trait 为闭包创建别名,这样我就不必在整个代码中多次重复声明,但是我不知道如何将 trait 转换回 Fn 以便我可以调用它总的来说,这可能吗?
trait Closure: Send + Sync {}
impl <F: Send + Sync> Closure for F where F: Fn(&str) -> bool {}
pub struct Struct {
pub closure: Box<dyn Closure>
}
impl Struct {
pub fn new(closure: impl Closure + 'static) -> Self {
Self{
closure: Box::new(closure)
}
}
}
pub fn main() {
let s = Struct::new(|f: &str| f.is_empty());
let result: bool = (s.closure)("hello world"); //TODO
println!("{}", result );
}
【问题讨论】:
-
闭包会一直是
Fn(&str) -> bool吗? -
是的,这个结构的参数和返回类型总是相同的
标签: rust