Trait 和生命周期约束(Bounds)
Syntax
Bounds → Bound ( + Bound )* +?
Bound → Lifetime | TraitBound | UseBound
TraitBound →
( ? | ForLifetimes )? TypePath
| ( ( ? | ForLifetimes )? TypePath )
LifetimeBounds → ( Lifetime + )* Lifetime?
Lifetime →
LIFETIME_OR_LABEL
| 'static
| '_
UseBound → use UseBoundGenericArgs
UseBoundGenericArgs →
< >
| < ( UseBoundGenericArg , )* UseBoundGenericArg ,? >
UseBoundGenericArg →
Lifetime
| IDENTIFIER
| Self
Trait 和生命周期约束为泛型项提供了一种方式来限制哪些类型和生命周期用作其参数。约束可以在 where 子句中的任何类型上提供。对于某些常见情况,还有更短的形式:
- 在声明泛型参数之后编写的约束:
fn f<A: Copy>() {}与fn f<A>() where A: Copy {}相同。 - 在 trait 声明中作为超级 trait:
trait Circle : Shape {}等同于trait Circle where Self : Shape {}。 - 在 trait 声明中作为关联类型的约束:
trait A { type B: Copy; }等同于trait A where Self::B: Copy { type B; }。
使用项时必须满足项上的约束。在对泛型项进行类型检查和借用检查时,约束可用于确定 trait 已为类型实现。例如,给定 Ty: Trait
- 在泛型函数的主体中,可以在
Ty值上调用Trait的方法。同样可以使用Trait上的关联常量。 - 可以使用
Trait的关联类型。 - 具有
T: Trait约束的泛型函数和类型可以使用Ty作为T。
#![allow(unused)]
fn main() {
type Surface = i32;
trait Shape {
fn draw(&self, surface: Surface);
fn name() -> &'static str;
}
fn draw_twice<T: Shape>(surface: Surface, sh: T) {
sh.draw(surface); // Can call method because T: Shape
sh.draw(surface);
}
fn copy_and_draw_twice<T: Copy>(surface: Surface, sh: T) where T: Shape {
let shape_copy = sh; // doesn't move sh because T: Copy
draw_twice(surface, sh); // Can use generic function because T: Shape
}
struct Figure<S: Shape>(S, S);
fn name_figure<U: Shape>(
figure: Figure<U>, // Type Figure<U> is well-formed because U: Shape
) {
println!(
"Figure of two {}",
U::name(), // Can use associated function
);
}
}
不使用项的参数或高阶生命周期的约束在定义项时检查。此类约束为 false 是错误的。
Copy、Clone 和 Sized 约束在使用项时也会针对某些泛型类型进行检查,即使使用不提供具体类型。在可变引用、trait 对象或切片上具有 Copy 或 Clone 作为约束是错误的。在 trait 对象或切片上具有 Sized 作为约束是错误的。
#![allow(unused)]
fn main() {
struct A<'a, T>
where
i32: Default, // Allowed, but not useful
i32: Iterator, // Error: `i32` is not an iterator
&'a mut T: Copy, // (at use) Error: the trait bound is not satisfied
[T]: Sized, // (at use) Error: size cannot be known at compilation
{
f: &'a T,
}
struct UsesA<'a, T>(A<'a, T>);
}
Trait 和生命周期约束也用于命名 trait 对象。
?Sized
? 仅用于放宽类型参数或关联类型的隐式 Sized trait 约束。?Sized 不能用作其他类型的约束。
生命周期约束
生命周期约束可以应用于类型或其他生命周期。
约束 'a: 'b 通常读作 'a 比 'b 活得更久。'a: 'b 意味着 'a 至少与 'b 持续一样长,因此引用 &'a () 在 &'b () 有效时有效。
#![allow(unused)]
fn main() {
fn f<'a, 'b>(x: &'a i32, mut y: &'b i32) where 'a: 'b {
y = x; // &'a i32 is a subtype of &'b i32 because 'a: 'b
let r: &'b &'a i32 = &&0; // &'b &'a i32 is well formed because 'a: 'b
}
}
T: 'a 意味着 T 的所有生命周期参数比 'a 活得更久。例如,如果 'a 是无约束的生命周期参数,则 i32: 'static 和 &'static str: 'a 被满足,但 Vec<&'a ()>: 'static 不被满足。
高阶 trait 约束
Syntax
ForLifetimes → for GenericParams
Trait 约束可以是高阶的关于生命周期。这些约束指定对所有生命周期都为 true 的约束。例如,约束如 for<'a> &'a T: PartialEq<i32> 将要求如下实现
#![allow(unused)]
fn main() {
struct T;
impl<'a> PartialEq<i32> for &'a T {
// ...
fn eq(&self, other: &i32) -> bool {true}
}
}
然后可以用于将任何生命周期的 &'a T 与 i32 进行比较。
这里只能使用高阶约束,因为引用的生命周期比函数上任何可能的生命周期参数都短:
#![allow(unused)]
fn main() {
fn call_on_ref_zero<F>(f: F) where for<'a> F: Fn(&'a i32) {
let zero = 0;
f(&zero);
}
}
高阶生命周期也可以在 trait 之前指定:唯一的区别是生命周期参数的[作用域]scope,它仅延伸到以下 trait 的末尾,而不是整个约束。此函数等同于上一个函数。
#![allow(unused)]
fn main() {
fn call_on_ref_zero<F>(f: F) where F: for<'a> Fn(&'a i32) {
let zero = 0;
f(&zero);
}
}
隐式约束
类型为 well-formed 所需的生命周期约束有时会被推断。
#![allow(unused)]
fn main() {
fn requires_t_outlives_a<'a, T>(x: &'a T) {}
}
类型参数 T 被要求比 'a 活得更久,以便类型 &'a T 为 well-formed。这是被推断的,因为函数签名包含类型 &'a T,该类型仅在 T: 'a 成立时有效。
隐式约束被添加到函数的所有参数和输出中。在 requires_t_outlives_a 内部,您可以假设 T: 'a 成立,即使您没有显式指定:
#![allow(unused)]
fn main() {
fn requires_t_outlives_a_not_implied<'a, T: 'a>() {}
fn requires_t_outlives_a<'a, T>(x: &'a T) {
// This compiles, because `T: 'a` is implied by
// the reference type `&'a T`.
requires_t_outlives_a_not_implied::<'a, T>();
}
}
#![allow(unused)]
fn main() {
fn requires_t_outlives_a_not_implied<'a, T: 'a>() {}
fn not_implied<'a, T>() {
// This errors, because `T: 'a` is not implied by
// the function signature.
requires_t_outlives_a_not_implied::<'a, T>();
}
}
只有生命周期约束被隐式推断,trait 约束仍然必须显式添加。因此以下示例会导致错误:
#![allow(unused)]
fn main() {
use std::fmt::Debug;
struct IsDebug<T: Debug>(T);
// error[E0277]: `T` doesn't implement `Debug`
fn doesnt_specify_t_debug<T>(x: IsDebug<T>) {}
}
生命周期约束也会为类型定义和 impl 块推断:
#![allow(unused)]
fn main() {
struct Struct<'a, T> {
// This requires `T: 'a` to be well-formed
// which is inferred by the compiler.
field: &'a T,
}
enum Enum<'a, T> {
// This requires `T: 'a` to be well-formed,
// which is inferred by the compiler.
//
// Note that `T: 'a` is required even when only
// using `Enum::OtherVariant`.
SomeVariant(&'a T),
OtherVariant,
}
trait Trait<'a, T: 'a> {}
// This would error because `T: 'a` is not implied by any type
// in the impl header.
// impl<'a, T> Trait<'a, T> for () {}
// This compiles as `T: 'a` is implied by the self type `&'a T`.
impl<'a, T> Trait<'a, T> for &'a T {}
}
Use 约束
某些约束列表可以包含 use<..> 约束来控制 impl Trait 抽象返回类型捕获哪些泛型参数。有关更多详细信息,请参阅精确捕获。