]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/generics.md
New upstream version 1.37.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / generics.md
1 # Generics
2
3 *Generics* is the topic of generalizing types and functionalities to broader
4 cases. This is extremely useful for reducing code duplication in many ways,
5 but can call for rather involving syntax. Namely, being generic requires
6 taking great care to specify over which types a generic type
7 is actually considered valid. The simplest and most common use of generics
8 is for type parameters.
9
10 A type parameter is specified as generic by the use of angle brackets and upper
11 [camel case][camelcase]: `<Aaa, Bbb, ...>`. "Generic type parameters" are
12 typically represented as `<T>`. In Rust, "generic" also describes anything that
13 accepts one or more generic type parameters `<T>`. Any type specified as a
14 generic type parameter is generic, and everything else is concrete (non-generic).
15
16 For example, defining a *generic function* named `foo` that takes an argument
17 `T` of any type:
18
19 ```rust,ignore
20 fn foo<T>(arg: T) { ... }
21 ```
22
23 Because `T` has been specified as a generic type parameter using `<T>`, it
24 is considered generic when used here as `(arg: T)`. This is the case even if `T`
25 has previously been defined as a `struct`.
26
27 This example shows some of the syntax in action:
28
29 ```rust,editable
30 // A concrete type `A`.
31 struct A;
32
33 // In defining the type `Single`, the first use of `A` is not preceded by `<A>`.
34 // Therefore, `Single` is a concrete type, and `A` is defined as above.
35 struct Single(A);
36 // ^ Here is `Single`s first use of the type `A`.
37
38 // Here, `<T>` precedes the first use of `T`, so `SingleGen` is a generic type.
39 // Because the type parameter `T` is generic, it could be anything, including
40 // the concrete type `A` defined at the top.
41 struct SingleGen<T>(T);
42
43 fn main() {
44 // `Single` is concrete and explicitly takes `A`.
45 let _s = Single(A);
46
47 // Create a variable `_char` of type `SingleGen<char>`
48 // and give it the value `SingleGen('a')`.
49 // Here, `SingleGen` has a type parameter explicitly specified.
50 let _char: SingleGen<char> = SingleGen('a');
51
52 // `SingleGen` can also have a type parameter implicitly specified:
53 let _t = SingleGen(A); // Uses `A` defined at the top.
54 let _i32 = SingleGen(6); // Uses `i32`.
55 let _char = SingleGen('a'); // Uses `char`.
56 }
57 ```
58
59 ### See also:
60
61 [`struct`s][structs]
62
63 [structs]: custom_types/structs.md
64 [camelcase]: https://en.wikipedia.org/wiki/CamelCase