Rust generics: Difference between revisions
From wikinotes
No edit summary |
|||
Line 14: | Line 14: | ||
let c = Coord{1, 2, 3}; // valid | let c = Coord{1, 2, 3}; // valid | ||
let c = Coord{1, 2u8, 3}; // invalid! 1/3 are i32, but 2u8 is a u8. | let c = Coord{1, 2u8, 3}; // invalid! 1/3 are i32, but 2u8 is a u8. | ||
</syntaxhighlight> | |||
Use as many generic types as you'd like within a signature,<br> | |||
they are not limited to a single character. | |||
<syntaxhighlight lang="rust"> | |||
struct Coord<X, Y, Z> { | |||
x: X, | |||
y: Y, | |||
z: Z, | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Example --> | </blockquote><!-- Example --> |
Revision as of 19:26, 8 February 2023
Generics allow you to abstract a function so that it accepts a range of types.
Functions, Structs, Enums etc. can all be expressed as generics
Example
// everywhere 'T' shows up, it represents the type. struct Coord<T> { x: T, y: T, z: T, } let c = Coord{1, 2, 3}; // valid let c = Coord{1, 2u8, 3}; // invalid! 1/3 are i32, but 2u8 is a u8.Use as many generic types as you'd like within a signature,
they are not limited to a single character.struct Coord<X, Y, Z> { x: X, y: Y, z: Z, }