← 中文资源

简体中文版本

trait 关联类型定义

在 trait 里声明 type Output,让每个实现类自行决定返回类型;泛型函数再用 T::Output 约束 Display,避免额外的泛型参数。

阅读英文原文

实现说明

主线是函数 summarize、print_summary、main的调用过程。

使用要点

  • main 按顺序串起 print_summary;运行文件就会把这个流程跑一遍。

常见问题

「trait 关联类型定义」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

签名一览:fn summarize(&self) -> Self::Output;

核心语句

fn summarize(&self) -> Self::Output;
fn summarize(&self) -> String {
    self.title.clone()
}
fn summarize(&self) -> usize {
    self.lines.len()
}

代码示例

use std::fmt::Display;

// Associated types in trait definitions: each implementation chooses Output
trait Summary {
    type Output;

    fn summarize(&self) -> Self::Output;
}

struct Report {
    lines: Vec<String>,
}

impl Summary for Report {
    type Output = usize;

    fn summarize(&self) -> usize {
        self.lines.len()
    }
}

struct Entry {
    title: String,
}

impl Summary for Entry {
    type Output = String;

    fn summarize(&self) -> String {
        self.title.clone()
    }
}

fn print_summary<T>(item: &T)
where
    T: Summary,
    T::Output: Display,
{
    println!("{}", item.summarize());
}

fn main() {
    let report = Report {
        lines: vec![String::from("a"), String::from("b")],
    };
    let entry = Entry {
        title: String::from("traits"),
    };

    print_summary(&report);
    print_summary(&entry);
}