What is the Rust type keyword?

A simple type Foo = Bar; outside of an impl defines a type alias, and is documented in The Book. There’s a generic version type Foo<T> = ... but if you understand generics in general then this is an obvious extension.

type in an impl defines an associated type. They are documented in The Book, but I’ve already written a short summary, so you get that too:

When you have a trait like Add, you want to abstract not only over what types of things can be added, but also over the type of their sum. Adding integers results in integers, adding floats results in floats. But you don’t want the result type to be a parameter of Add as in Add<ThingToAdd, ResultType>, for reasons that I’ll skim over here.

Therefore, the trait comes with a type that’s associated with the impl. Given any implementation of Add, e.g., impl Add<Foo> for Bar, the type of the addition result is already determined. This is declared in the trait like this:

trait Add<Rhs> {
    type Result;
    // ...
}

And then all implementations define what the type of their result is:

impl Add<Foo> for Bar {
    type Result = BarPlusFoo;
    // ...
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)