Simple Generics

Generics are fundamental for Rust.

Generic Structs

struct Point<Precision> {
    x: Precision,
    y: Precision
}

fn main() {
    let point = Point { x: 1_u32, y: 2 };
    let point: Point<i32> = Point { x: 1, y: 2 };
}

Type Inference

Rust finds the types of all variables and generics with sufficient information.

This only applies inside of function bodies.

Signatures must always be fully specified.

Generic Enums

enum Either<T, X> {
    Left(T),
    Right(X),
}

fn main() {
    let alternative: Either<i32, f64> = Either::Left(123);
}

enum Result<T,E> {
    Ok(T),
    Err(E),
}

enum Option<T> {
    Some(T),
    None,
}

Generic Functions

Generic Functions have type parameters.

fn accept_any_type<T>(arg: T) {
    // ...
}

fn accept_and_return_any_type<T, U>(arg: T) -> U {
    // ...
}

Generic functions are used when computations can be expressed in an abstract way.