泛型

泛型是将类型和功能推广到更广泛情况的主题。这对于在许多方面减少代码重复非常有用,但可能需要相当复杂的语法。 也就是说,要保持泛型,需要非常小心地指定泛型类型实际上在哪些类型上被认为是有效的。 泛型最简单和最常见的用途是用于类型参数。

类型参数通过使用尖括号和上驼峰式命名法指定为泛型:<Aaa, Bbb, ...>。“泛型类型参数”通常表示为 <T>。在 Rust 中,“泛型”也描述接受一个或多个泛型类型参数 <T> 的任何内容。任何指定为泛型类型参数的类型都是泛型,其他所有类型都是具体的(非泛型)。

例如,定义一个名为 foo泛型函数,它接受任何类型的参数 T

fn foo<T>(arg: T) { ... }

因为 T 已使用 <T> 指定为泛型类型参数,所以在此处用作 (arg: T) 时,它被认为是泛型的。即使 T 之前已定义为 struct,也是如此。

此示例展示了一些实际应用的语法

// A concrete type `A`.
struct A;

// In defining the type `Single`, the first use of `A` is not preceded by `<A>`.
// Therefore, `Single` is a concrete type, and `A` is defined as above.
struct Single(A);
//            ^ Here is `Single`s first use of the type `A`.

// Here, `<T>` precedes the first use of `T`, so `SingleGen` is a generic type.
// Because the type parameter `T` is generic, it could be anything, including
// the concrete type `A` defined at the top.
struct SingleGen<T>(T);

fn main() {
    // `Single` is concrete and explicitly takes `A`.
    let _s = Single(A);
    
    // Create a variable `_char` of type `SingleGen<char>`
    // and give it the value `SingleGen('a')`.
    // Here, `SingleGen` has a type parameter explicitly specified.
    let _char: SingleGen<char> = SingleGen('a');

    // `SingleGen` can also have a type parameter implicitly specified:
    let _t    = SingleGen(A); // Uses `A` defined at the top.
    let _i32  = SingleGen(6); // Uses `i32`.
    let _char = SingleGen('a'); // Uses `char`.
}

另请参阅

结构体