type SomeSub = dyn for<'a> Fn(&'a str) -> &'a str;
,我想将其与具有显式生命周期的 Box 一起使用,如
Box<SomeSub + 'b>
。不幸的是这不能编译:
type SomeSub = dyn for<'a> Fn(&'a str) -> &'a str;
struct SomeBuilder(pub usize);
impl SomeBuilder {
// --> this gets rejected with "type aliases cannot be used as traits"
fn get_closure<'o>(
&'o self
) -> Box<dyn SomeSub + 'o> {
Box::new(|s| &s[self.0..])
}
// This works, but duplicates the code of the type alias
fn get_closure_long<'o>(
&'o self
) -> Box<dyn for<'a> Fn(&'a str) -> &'a str + 'o> {
Box::new(|s| &s[self.0..])
}
}
第二种方法 get_closure_long()
编译时,
get_closure()
会导致错误:
error[E0404]: expected trait, found type alias `SomeSub`
--> src/lib.rs:8:18
|
8 | ) -> Box<dyn SomeSub + 'o> {
| ^^^^^^^ type aliases cannot be used as traits
像 dyn
一样省略
-> Box<SomeSub + 'o>
将被拒绝,并显示“类型别名不能用作特征”。使用
Box<SomeSub>
工作机器人不允许闭包捕获任何引用。将闭包类型别名与 Box 以及该框的显式生命周期相结合的正确方法是什么?