使用 `where` 子句实现富有表现力的 Rust 泛型

RustRustBeginner
立即练习

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

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

简介

在本实验中,我们了解到 Rust 中的 where 子句可用于在声明泛型类型时单独表达其边界,从而使语法更清晰,并且还可以将边界应用于任意类型,而不仅仅是类型参数。当边界比普通语法更具表现力时,where 子句特别有用,如涉及 PrintInOption 特征的示例所示。

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/DataTypesGroup(["Data Types"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/MemorySafetyandManagementGroup(["Memory Safety and Management"]) rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/AdvancedTopicsGroup(["Advanced Topics"]) rust(("Rust")) -.-> rust/BasicConceptsGroup(["Basic Concepts"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("Variable Declarations") rust/DataTypesGroup -.-> rust/type_casting("Type Conversion and Casting") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("Lifetime Specifiers") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") rust/AdvancedTopicsGroup -.-> rust/traits("Traits") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("Traits for Operator Overloading") subgraph Lab Skills rust/variable_declarations -.-> lab-99351{{"使用 `where` 子句实现富有表现力的 Rust 泛型"}} rust/type_casting -.-> lab-99351{{"使用 `where` 子句实现富有表现力的 Rust 泛型"}} rust/function_syntax -.-> lab-99351{{"使用 `where` 子句实现富有表现力的 Rust 泛型"}} rust/expressions_statements -.-> lab-99351{{"使用 `where` 子句实现富有表现力的 Rust 泛型"}} rust/lifetime_specifiers -.-> lab-99351{{"使用 `where` 子句实现富有表现力的 Rust 泛型"}} rust/method_syntax -.-> lab-99351{{"使用 `where` 子句实现富有表现力的 Rust 泛型"}} rust/traits -.-> lab-99351{{"使用 `where` 子句实现富有表现力的 Rust 泛型"}} rust/operator_overloading -.-> lab-99351{{"使用 `where` 子句实现富有表现力的 Rust 泛型"}} end

where 子句

边界也可以使用紧跟在左花括号 { 之前的 where 子句来表达,而不是在类型首次出现时表达。此外,where 子句可以将边界应用于任意类型,而不仅仅是类型参数。

where 子句有用的一些情况:

  • 当分别指定泛型类型和边界更清晰时:
impl <A: TraitB + TraitC, D: TraitE + TraitF> MyTrait<A, D> for YourType {}

// 使用 `where` 子句表达边界
impl <A, D> MyTrait<A, D> for YourType where
    A: TraitB + TraitC,
    D: TraitE + TraitF {}
  • 当使用 where 子句比使用普通语法更具表现力时。在这个例子中,如果没有 where 子句,impl 无法直接表达:
use std::fmt::Debug;

trait PrintInOption {
    fn print_in_option(self);
}

// 因为否则我们将不得不表示为 `T: Debug` 或者
// 使用另一种间接方法,所以这需要一个 `where` 子句:
impl<T> PrintInOption for T where
    Option<T>: Debug {
    // 我们希望 `Option<T>: Debug` 作为我们的边界,因为这是要打印的内容。否则会使用错误的边界。
    fn print_in_option(self) {
        println!("{:?}", Some(self));
    }
}

fn main() {
    let vec = vec![1, 2, 3];

    vec.print_in_option();
}

总结

恭喜你!你已完成“where 子句”实验。你可以在 LabEx 中练习更多实验来提升你的技能。