泛型参数
语法
GenericParams :
<>
|<(GenericParam,)* GenericParam,?>GenericParam :
OuterAttribute* ( LifetimeParam | TypeParam | ConstParam )LifetimeParam :
Lifetime (:LifetimeBounds )?TypeParam :
IDENTIFIER (:TypeParamBounds? )? (=Type )?ConstParam:
constIDENTIFIER:Type (=Block | IDENTIFIER | -?LITERAL )?
函数、类型别名、结构体、枚举、联合体、trait 和实现可以通过类型、常量和生命周期进行参数化。这些参数通常列在尖括号(<...>)中,紧跟在项的名称之后、其定义之前。对于没有名称的实现,它们直接跟在 impl 之后。
泛型参数的顺序仅限于生命周期参数,然后是类型参数和常量参数混合排列。
在 GenericParams 列表中,同一个参数名称不能声明多次。
带有类型、常量和生命周期参数的一些项的例子
#![allow(unused)] fn main() { fn foo<'a, T>() {} trait A<U> {} struct Ref<'a, T> where T: 'a { r: &'a T } struct InnerArray<T, const N: usize>([T; N]); struct EitherOrderWorks<const N: bool, U>(U); }
泛型参数在其声明的项定义范围内有效。正如项声明中所述,它们在函数体中声明的项内无效。有关更多详细信息,请参见泛型参数作用域。
引用、裸指针、数组、切片、元组和函数指针也具有生命周期或类型参数,但不用路径语法来引用它们。
'_ 和 'static 不是有效的生命周期参数名称。
常量泛型
常量泛型参数允许项对常量值进行泛型化。
const 标识符在值命名空间中为常量参数引入一个名称,并且该项的所有实例都必须使用给定类型的值来实例化。
常量参数唯一允许的类型是 u8、u16、u32、u64、u128、usize、i8、i16、i32、i64、i128、isize、char 和 bool。
常量参数可以在任何可以使用常量项的地方使用,但当它们用于类型或数组重复表达式时,必须是独立的(如下所述)。也就是说,它们允许出现在以下位置:
- 作为应用于所讨论项签名一部分的任何类型的常量。
- 作为用于定义关联常量的常量表达式的一部分,或作为关联类型的参数。
- 作为该项中任何函数体内的任何运行时表达式中的值。
- 作为该项中任何函数体中使用的任何类型的参数。
- 作为该项中任何字段类型的一部分。
#![allow(unused)] fn main() { // Examples where const generic parameters can be used. // Used in the signature of the item itself. fn foo<const N: usize>(arr: [i32; N]) { // Used as a type within a function body. let x: [i32; N]; // Used as an expression. println!("{}", N * 2); } // Used as a field of a struct. struct Foo<const N: usize>([i32; N]); impl<const N: usize> Foo<N> { // Used as an associated constant. const CONST: usize = N * 4; } trait Trait { type Output; } impl<const N: usize> Trait for Foo<N> { // Used as an associated type. type Output = [i32; N]; } }
#![allow(unused)] fn main() { // Examples where const generic parameters cannot be used. fn foo<const N: usize>() { // Cannot use in item definitions within a function body. const BAD_CONST: [usize; N] = [1; N]; static BAD_STATIC: [usize; N] = [1; N]; fn inner(bad_arg: [usize; N]) { let bad_value = N * 2; } type BadAlias = [usize; N]; struct BadStruct([usize; N]); } }
作为进一步的限制,常量参数只能作为独立参数出现在类型或数组重复表达式内部。在这些上下文中,它们只能用作单个段的路径表达式,可能在块内(例如 N 或 {N})。也就是说,它们不能与其他表达式组合。
#![allow(unused)] fn main() { // Examples where const parameters may not be used. // Not allowed to combine in other expressions in types, such as the // arithmetic expression in the return type here. fn bad_function<const N: usize>() -> [u8; {N + 1}] { // Similarly not allowed for array repeat expressions. [1; {N + 1}] } }
在路径中的常量参数指定了该项要使用的常量值。
参数必须是赋予常量参数类型的常量表达式。常量表达式必须是块表达式(用花括号包围),除非它是单个路径段(一个IDENTIFIER)或字面量(可能带有前导 - 符号)。
注意
这个语法限制是必要的,以避免在解析类型内部的表达式时需要无限向前查看。
#![allow(unused)] fn main() { fn double<const N: i32>() { println!("doubled: {}", N * 2); } const SOME_CONST: i32 = 12; fn example() { // Example usage of a const argument. double::<9>(); double::<-123>(); double::<{7 + 8}>(); double::<SOME_CONST>(); double::<{ SOME_CONST + 5 }>(); } }
当泛型参数可能被解析为类型参数或常量参数而存在歧义时,它总是被解析为类型。将参数放在块表达式中可以强制将其解释为常量参数。
#![allow(unused)] fn main() { type N = u32; struct Foo<const N: usize>; // The following is an error, because `N` is interpreted as the type alias `N`. fn foo<const N: usize>() -> Foo<N> { todo!() } // ERROR // Can be fixed by wrapping in braces to force it to be interpreted as the `N` // const parameter: fn bar<const N: usize>() -> Foo<{ N }> { todo!() } // ok }
与类型参数和生命周期参数不同,常量参数可以声明而不在参数化的项中使用,泛型实现中描述的实现除外。
#![allow(unused)] fn main() { // ok struct Foo<const N: usize>; enum Bar<const M: usize> { A, B } // ERROR: unused parameter struct Baz<T>; struct Biz<'a>; struct Unconstrained; impl<const N: usize> Unconstrained {} }
在解析 trait 约束义务时,在确定约束是否满足时,不考虑常量参数所有实现的穷举性。例如,在下面的例子中,即使 bool 类型的所有可能常量值都已实现,但 trait 约束未满足仍然是一个错误:
#![allow(unused)] fn main() { struct Foo<const B: bool>; trait Bar {} impl Bar for Foo<true> {} impl Bar for Foo<false> {} fn needs_bar(_: impl Bar) {} fn generic<const B: bool>() { let v = Foo::<B>; needs_bar(v); // ERROR: trait bound `Foo<B>: Bar` is not satisfied } }
Where 从句
语法
WhereClause :
where( WhereClauseItem,)* WhereClauseItem ?WhereClauseItem :
LifetimeWhereClauseItem
| TypeBoundWhereClauseItemLifetimeWhereClauseItem :
Lifetime:LifetimeBoundsTypeBoundWhereClauseItem :
ForLifetimes? Type:TypeParamBounds?
Where 从句提供了另一种指定类型和生命周期参数约束的方式,同时也提供了一种指定非类型参数的类型约束的方式。
for 关键字可用于引入高阶生命周期。它只允许使用 LifetimeParam 参数。
#![allow(unused)] fn main() { struct A<T> where T: Iterator, // Could use A<T: Iterator> instead T::Item: Copy, // Bound on an associated type String: PartialEq<T>, // Bound on `String`, using the type parameter i32: Default, // Allowed, but not useful { f: T, } }
属性
泛型生命周期参数和类型参数允许在其上使用属性。在这个位置没有内置的属性会做任何事情,但自定义 derive 属性可能会赋予其意义。
此示例展示了如何使用自定义 derive 属性修改泛型参数的含义。
// Assume that the derive for MyFlexibleClone declared `my_flexible_clone` as
// an attribute it understands.
#[derive(MyFlexibleClone)]
struct Foo<#[my_flexible_clone(unbounded)] H> {
a: *const H
}