我正在读async book.section async lifetimes
中有一段代码片段的语法我不熟悉:
fn foo_expanded<'a>(x: &'a u8) -> impl Future<Output = u8> + 'a {
async move { *x }
}
在impl Future<Output = u8> + 'a
中,impl Trait + 'lifetime
是什么?
更新:我更多的是问它是什么,而不是终身逻辑的解释.官方文件中的定义如下:
我正在读async book.section async lifetimes
中有一段代码片段的语法我不熟悉:
fn foo_expanded<'a>(x: &'a u8) -> impl Future<Output = u8> + 'a {
async move { *x }
}
在impl Future<Output = u8> + 'a
中,impl Trait + 'lifetime
是什么?
更新:我更多的是问它是什么,而不是终身逻辑的解释.官方文件中的定义如下:
这里
impl Trait + 'lifetime
是多少?
它是一个Impl特征,这里特别用作抽象返回类型
Impl特征
Syntax
ImplTraitType : impl TypeParamBounds ImplTraitTypeOneBound : impl TraitBound
impl
Trait提供了指定未命名但具体的类型的方法trait Trait {} // argument position: anonymous type parameter fn foo(arg: impl Trait) { } // return position: abstract return type fn bar() -> impl Trait { }
其中the grammar of TypeParamBounds
允许特征和生命周期 界限
特征和生命周期 界限
Syntax
TypeParamBounds : TypeParamBound ( + TypeParamBound )* +? TypeParamBound : Lifetime | TraitBound TraitBound : ?? ForLifetimes? TypePath | ( ?? ForLifetimes? TypePath ) LifetimeBounds : ( Lifetime + )* Lifetime? Lifetime : LIFETIME_OR_LABEL | 'static | '_
特别注意,TypeParamBounds
的语法是一个或可选地几个TypeParamBound
的组合,每个TypeParamBound
依次是TraitBound
或Lifetime
(边界).
Specifying Multiple Trait Bounds with the + Syntax详细描述了我们可以组合多个特征界限,但这同样适用于生命周期 界限(在语法允许的情况下).有人可能会争辩说,这一节还应该提到生命周期 界限.