我有一个类似type SomeSub = dyn for<'a> Fn(&'a str) -> &'a str;
的FN特征的类型别名,我想将其与具有明确生命周期的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>
Works bot不允许闭包捕获任何引用.
将闭包类型别名与Box以及该Box的显式生存期相结合的正确方法是什么?