Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

关联项

Syntax
AssociatedItem
    OuterAttribute* (
        MacroInvocationSemi
      | ( Visibility? ( TypeAlias | ConstantItem | Function ) )
    )

关联项是在 trait 中声明或在实现中定义的项。它们之所以被称为关联项,是因为它们定义在关联类型上 — 即实现中的类型。

它们是您可以在模块中声明的项类型的子集。具体来说,有关联函数(包括方法)、关联类型关联常量

当关联项在逻辑上与关联项相关时,关联项很有用。例如,Option 上的 is_some 方法本质上与 Options 相关,因此应该关联。

每种关联项都有两种变体:包含实际实现的定义和声明签名的声明。

正是声明构成了 trait 的契约以及泛型类型上可用的内容。

关联函数和方法

关联函数是与类型关联的函数

关联函数声明为关联函数定义声明签名。它被编写为函数项,只是函数主体被替换为 ;

标识符是函数的名称。

关联函数的泛型、参数列表、返回类型和 where 子句必须与关联函数声明的相同。

关联函数定义定义与另一个类型关联的函数。它的编写方式与函数项相同。

Note

一个常见的示例是名为 new 的关联函数,它返回与其关联的类型的值。

struct Struct {
    field: i32
}

impl Struct {
    fn new() -> Struct {
        Struct {
            field: 0i32
        }
    }
}

fn main () {
    let _struct = Struct::new();
}

当关联函数在 trait 上声明时,也可以使用作为到 trait 的路径后跟 trait 名称的路径来调用该函数。当发生这种情况时,它被替换为 <_ as Trait>::function_name

#![allow(unused)]
fn main() {
trait Num {
    fn from_i32(n: i32) -> Self;
}

impl Num for f64 {
    fn from_i32(n: i32) -> f64 { n as f64 }
}

// These 4 are all equivalent in this case.
let _: f64 = Num::from_i32(42);
let _: f64 = <_ as Num>::from_i32(42);
let _: f64 = <f64 as Num>::from_i32(42);
let _: f64 = f64::from_i32(42);
}

方法

第一个参数名为 self 的关联函数称为方法,可以使用方法调用运算符调用,例如 x.foo(),以及通常的函数调用表示法。

如果指定了 self 参数的类型,则它仅限于解析为以下语法生成的类型(其中 'lt 表示某个任意生命周期):

P = &'lt S | &'lt mut S | Box<S> | Rc<S> | Arc<S> | Pin<P>
S = Self | P

此语法中的 Self 终端表示解析为实现类型的类型。这也可以包括上下文类型别名 Self、其他类型别名或解析为实现类型的关联类型投影。

#![allow(unused)]
fn main() {
use std::rc::Rc;
use std::sync::Arc;
use std::pin::Pin;
// Examples of methods implemented on struct `Example`.
struct Example;
type Alias = Example;
trait Trait { type Output; }
impl Trait for Example { type Output = Example; }
impl Example {
    fn by_value(self: Self) {}
    fn by_ref(self: &Self) {}
    fn by_ref_mut(self: &mut Self) {}
    fn by_box(self: Box<Self>) {}
    fn by_rc(self: Rc<Self>) {}
    fn by_arc(self: Arc<Self>) {}
    fn by_pin(self: Pin<&Self>) {}
    fn explicit_type(self: Arc<Example>) {}
    fn with_lifetime<'a>(self: &'a Self) {}
    fn nested<'a>(self: &mut &'a Arc<Rc<Box<Alias>>>) {}
    fn via_projection(self: <Example as Trait>::Output) {}
}
}

可以使用简写语法而不指定类型,它们具有以下等效形式:

简写等效形式
selfself: Self
&'lifetime selfself: &'lifetime Self
&'lifetime mut selfself: &'lifetime mut Self

Note

使用此简写时,生命周期可以并且通常会被省略。

如果 self 参数以 mut 为前缀,则它成为可变变量,类似于使用 mut 标识符模式的常规参数。例如:

#![allow(unused)]
fn main() {
trait Changer: Sized {
    fn change(mut self) {}
    fn modify(mut self: Box<Self>) {}
}
}

作为 trait 上方法的示例,请考虑以下内容:

#![allow(unused)]
fn main() {
type Surface = i32;
type BoundingBox = i32;
trait Shape {
    fn draw(&self, surface: Surface);
    fn bounding_box(&self) -> BoundingBox;
}
}

这定义了一个具有两个方法的 trait。所有具有此 trait 的实现的值(当 trait 在作用域中时)都可以调用其 drawbounding_box 方法。

#![allow(unused)]
fn main() {
type Surface = i32;
type BoundingBox = i32;
trait Shape {
    fn draw(&self, surface: Surface);
    fn bounding_box(&self) -> BoundingBox;
}

struct Circle {
    // ...
}

impl Shape for Circle {
    // ...
  fn draw(&self, _: Surface) {}
  fn bounding_box(&self) -> BoundingBox { 0i32 }
}

impl Circle {
    fn new() -> Circle { Circle{} }
}

let circle_shape = Circle::new();
let bounding_box = circle_shape.bounding_box();
}

2018 Edition differences

在 2015 版本中,可以使用匿名参数声明 trait 方法(例如 fn foo(u8))。这已弃用,从 2018 版本开始成为错误。所有参数必须有参数名称。

方法参数上的属性

方法参数上的属性遵循与常规函数参数相同的规则和限制。

关联类型

关联类型是与另一个类型关联的类型别名

关联类型不能在固有实现中定义,也不能在 trait 中给出默认实现。

关联类型声明为关联类型定义声明签名。它以以下形式之一编写,其中 Assoc 是关联类型的名称,Params 是类型、生命周期或 const 参数的逗号分隔列表,Bounds 是关联类型必须满足的 trait 约束的加号分隔列表,WhereBounds 是参数必须满足的约束的逗号分隔列表:

type Assoc;
type Assoc: Bounds;
type Assoc<Params>;
type Assoc<Params>: Bounds;
type Assoc<Params> where WhereBounds;
type Assoc<Params>: Bounds where WhereBounds;

标识符是声明的类型别名的名称。

可选的 trait 约束必须由类型别名的实现满足。

关联类型上有一个隐式的 Sized 约束,可以使用特殊的 ?Sized 约束来放宽。

关联类型定义为 trait 在类型上的实现定义类型别名。

它们的编写方式类似于关联类型声明,但不能包含 Bounds,而必须包含 Type

type Assoc = Type;
type Assoc<Params> = Type; // the type `Type` here may reference `Params`
type Assoc<Params> = Type where WhereBounds;
type Assoc<Params> where WhereBounds = Type; // deprecated, prefer the form above

如果类型 Item 从 trait Trait 具有关联类型 Assoc,则 <Item as Trait>::Assoc 是关联类型定义中指定类型的别名。

此外,如果 Item 是类型参数,则 Item::Assoc 可以在类型参数中使用。

关联类型可以包含泛型参数where 子句;这些通常称为泛型关联类型GAT。如果类型 Thing 从具有泛型 <'a> 的 trait Trait 具有关联类型 Item,则该类型可以命名为 <Thing as Trait>::Item<'x>,其中 'x 是作用域中的某个生命周期。在这种情况下,'x 将在 impl 上的关联类型定义中 'a 出现的任何地方使用。

trait AssociatedType {
    // Associated type declaration
    type Assoc;
}

struct Struct;

struct OtherStruct;

impl AssociatedType for Struct {
    // Associated type definition
    type Assoc = OtherStruct;
}

impl OtherStruct {
    fn new() -> OtherStruct {
        OtherStruct
    }
}

fn main() {
    // Usage of the associated type to refer to OtherStruct as <Struct as AssociatedType>::Assoc
    let _other_struct: OtherStruct = <Struct as AssociatedType>::Assoc::new();
}

具有泛型和 where 子句的关联类型的示例:

struct ArrayLender<'a, T>(&'a mut [T; 16]);

trait Lend {
    // Generic associated type declaration
    type Lender<'a> where Self: 'a;
    fn lend<'a>(&'a mut self) -> Self::Lender<'a>;
}

impl<T> Lend for [T; 16] {
    // Generic associated type definition
    type Lender<'a> = ArrayLender<'a, T> where Self: 'a;

    fn lend<'a>(&'a mut self) -> Self::Lender<'a> {
        ArrayLender(self)
    }
}

fn borrow<'a, T: Lend>(array: &'a mut T) -> <T as Lend>::Lender<'a> {
    array.lend()
}

fn main() {
    let mut array = [0usize; 16];
    let lender = borrow(&mut array);
}

关联类型容器示例

考虑以下 Container trait 的示例。请注意,该类型可在方法签名中使用:

#![allow(unused)]
fn main() {
trait Container {
    type E;
    fn empty() -> Self;
    fn insert(&mut self, elem: Self::E);
}
}

为了使类型实现此 trait,它不仅必须为每个方法提供实现,还必须指定类型 E。这是标准库类型 VecContainer 实现:

#![allow(unused)]
fn main() {
trait Container {
    type E;
    fn empty() -> Self;
    fn insert(&mut self, elem: Self::E);
}
impl<T> Container for Vec<T> {
    type E = T;
    fn empty() -> Vec<T> { Vec::new() }
    fn insert(&mut self, x: T) { self.push(x); }
}
}

BoundsWhereBounds 之间的关系

在此示例中:

#![allow(unused)]
fn main() {
use std::fmt::Debug;
trait Example {
    type Output<T>: Ord where T: Debug;
}
}

给定对关联类型的引用如 <X as Example>::Output<Y>,关联类型本身必须是 Ord,类型 Y 必须是 Debug

泛型关联类型上的必需 where 子句

trait 上的泛型关联类型声明目前可能需要 where 子句列表,具体取决于 trait 中的函数以及 GAT 的使用方式。这些规则将来可能会放宽;更新可以在泛型关联类型倡议仓库上找到。

简而言之,需要这些 where 子句是为了最大化 impl 中关联类型的允许定义。为此,任何可以证明成立的关于函数(使用函数或 trait 的参数)的子句,其中 GAT 作为输入或输出出现,也必须写在 GAT 本身上。

#![allow(unused)]
fn main() {
trait LendingIterator {
    type Item<'x> where Self: 'x;
    fn next<'a>(&'a mut self) -> Self::Item<'a>;
}
}

在上面的 next 函数中,我们可以证明 Self: 'a,因为来自 &'a mut self 的隐式约束;因此,我们必须在 GAT 本身上编写等效的约束:where Self: 'x

当 trait 中有多个函数使用 GAT 时,使用来自不同函数的约束的交集,而不是并集。

#![allow(unused)]
fn main() {
trait Check<T> {
    type Checker<'x>;
    fn create_checker<'a>(item: &'a T) -> Self::Checker<'a>;
    fn do_check(checker: Self::Checker<'_>);
}
}

在此示例中,type Checker<'a>; 不需要任何约束。虽然我们在 create_checker 上知道 T: 'a,但在 do_check 上不知道。但是,如果 do_check 被注释掉,则 Checker 上需要 where T: 'x 约束。

关联类型上的约束也会传播必需的 where 子句。

#![allow(unused)]
fn main() {
trait Iterable {
    type Item<'a> where Self: 'a;
    type Iterator<'a>: Iterator<Item = Self::Item<'a>> where Self: 'a;
    fn iter<'a>(&'a self) -> Self::Iterator<'a>;
}
}

这里,Item 上需要 where Self: 'a 是因为 iter。然而,Item 用于 Iterator 的约束中,where Self: 'a 子句在那里也需要。

最后,trait 上 GAT 的任何显式 'static 使用不计入必需的约束。

#![allow(unused)]
fn main() {
trait StaticReturn {
    type Y<'a>;
    fn foo(&self) -> Self::Y<'static>;
}
}

关联常量

关联常量是与类型关联的常量

关联常量声明为关联常量定义声明签名。它被编写为 const,然后是标识符,然后是 :,然后是类型,以 ; 结束。

标识符是路径中使用的常量名称。类型是定义必须实现的类型。

关联常量定义定义与类型关联的常量。它的编写方式与常量项相同。

关联常量定义仅在被引用时才进行常量求值。此外,包含泛型参数的定义在单态化后求值。

struct Struct;
struct GenericStruct<const ID: i32>;

impl Struct {
    // Definition not immediately evaluated
    const PANIC: () = panic!("compile-time panic");
}

impl<const ID: i32> GenericStruct<ID> {
    // Definition not immediately evaluated
    const NON_ZERO: () = if ID == 0 {
        panic!("contradiction")
    };
}

fn main() {
    // Referencing Struct::PANIC causes compilation error
    let _ = Struct::PANIC;

    // Fine, ID is not 0
    let _ = GenericStruct::<1>::NON_ZERO;

    // Compilation error from evaluating NON_ZERO with ID=0
    let _ = GenericStruct::<0>::NON_ZERO;
}

关联常量示例

基本示例:

trait ConstantId {
    const ID: i32;
}

struct Struct;

impl ConstantId for Struct {
    const ID: i32 = 1;
}

fn main() {
    assert_eq!(1, Struct::ID);
}

使用默认值:

trait ConstantIdDefault {
    const ID: i32 = 1;
}

struct Struct;
struct OtherStruct;

impl ConstantIdDefault for Struct {}

impl ConstantIdDefault for OtherStruct {
    const ID: i32 = 5;
}

fn main() {
    assert_eq!(1, Struct::ID);
    assert_eq!(5, OtherStruct::ID);
}