泛型
泛型(Generics)是关于将类型和功能通用化以适用于更广泛情况的主题。这在许多方面对于减少代码重复非常有帮助,但可能需要相当复杂的语法。具体来说,使用泛型需要非常小心地指定泛型类型实际上适用于哪些类型。泛型最简单、最常见的用途是类型参数。
类型参数通过使用尖括号和大驼峰命名法指定为泛型:<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`. }