Rust generics

From wikinotes
Revision as of 19:24, 8 February 2023 by Will (talk | contribs) (Created page with "Generics allow you to abstract a function so that it accepts a range of types.<br> Functions, Structs etc. can all be expressed as generics = Example = <blockquote> <syntaxhighlight lang="rust"> // 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. </syntaxhighlight> </blockquote><!-- Example -->")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Generics allow you to abstract a function so that it accepts a range of types.
Functions, Structs 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.