如何使用 dyn 类型别名将生命周期参数添加到 Box<>

问题描述 投票:0回答:1
我有一个 Fn 特征的类型别名,如

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 以及该框的显式生命周期相结合的正确方法是什么?

rust lifetime trait-objects
1个回答
0
投票
您可以使类型别名通用:

type SomeSub<'b> = dyn for<'a> Fn(&'a str) -> &'a str + 'b;
那么 

SomeSub<'o>

 是一个包含生命周期的有效类型,因此可以编译:

fn get_closure<'o>(&'o self) -> Box<SomeSub<'o>> { Box::new(|s| &s[self.0..]) }

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.