Rust generics: Difference between revisions

From wikinotes
(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 -->")
 
No edit summary
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
Generics allow you to abstract a function so that it accepts a range of types.<br>
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
Functions, Structs, Enums etc. can all be expressed as generics


= Example =
= Basics =
<blockquote>
<blockquote>
<syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">
Line 15: Line 15:
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>
</syntaxhighlight>
</blockquote><!-- Example -->
 
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<XVAL, YVAL, ZVAL> {
    x: XVAL,
    y: YVAL,
    z: ZVAL,
}
</syntaxhighlight>
</blockquote><!-- Basics -->
 
= Require Trait Implementor =
<blockquote>
You can also require that an object implements a specific trait.
See more details in [[rust traits]]
 
Implements single trait
<syntaxhighlight lang="rust">
fn play_with_pet<P: Pet>(pet: P) -> bool {}
</syntaxhighlight>
 
Implements multiple traits
<syntaxhighlight lang="rust">
// with impl
fn play_with_pet(pet: &(impl Pet + Display)) -> bool {}
 
// with where clause
fn play_with_pet<P>(p: P) -> bool
where
    P: Pet + Display
{}
</syntaxhighlight>
</blockquote><!-- Require Trait Implementor -->

Latest revision as of 21:15, 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

Basics

// 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<XVAL, YVAL, ZVAL> {
    x: XVAL,
    y: YVAL,
    z: ZVAL,
}

Require Trait Implementor

You can also require that an object implements a specific trait. See more details in rust traits

Implements single trait

fn play_with_pet<P: Pet>(pet: P) -> bool {}

Implements multiple traits

// with impl
fn play_with_pet(pet: &(impl Pet + Display)) -> bool {}

// with where clause
fn play_with_pet<P>(p: P) -> bool
where
    P: Pet + Display
{}