Rust 特性继承与组合

RustRustBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索如何在 Rust 中把 trait 定义为其他 trait 的超集,从而通过子 trait 来实现多个 trait。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,并通过 rustc main.rs &&./main 来编译和运行它。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/AdvancedTopicsGroup(["Advanced Topics"]) rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") rust/AdvancedTopicsGroup -.-> rust/traits("Traits") subgraph Lab Skills rust/function_syntax -.-> lab-99221{{"Rust 特性继承与组合"}} rust/expressions_statements -.-> lab-99221{{"Rust 特性继承与组合"}} rust/method_syntax -.-> lab-99221{{"Rust 特性继承与组合"}} rust/traits -.-> lab-99221{{"Rust 特性继承与组合"}} end

超级 trait

Rust 没有 “继承”,但你可以将一个 trait 定义为另一个 trait 的超集。例如:

trait Person {
    fn name(&self) -> String;
}

// Person 是 Student 的超级 trait。
// 实现 Student 要求你同时实现 Person。
trait Student: Person {
    fn university(&self) -> String;
}

trait Programmer {
    fn fav_language(&self) -> String;
}

// CompSciStudent(计算机科学专业的学生)是 Programmer 和 Student 的子 trait。
// 实现 CompSciStudent 要求你实现这两个超级 trait。
trait CompSciStudent: Programmer + Student {
    fn git_username(&self) -> String;
}

fn comp_sci_student_greeting(student: &dyn CompSciStudent) -> String {
    format!(
        "My name is {} and I attend {}. My favorite language is {}. My Git username is {}",
        student.name(),
        student.university(),
        student.fav_language(),
        student.git_username()
    )
}

fn main() {}

总结

恭喜你!你已经完成了“超级 trait”实验。你可以在 LabEx 中练习更多实验来提升你的技能。