Type aliases

Contents

Type aliases#

type introduces a new name; does not create a distinct type.

type UserId = u64;
type Result<T> = std::result::Result<T, MyError>;

For a distinct nominal type (so the compiler catches mixing), use a newtype struct.

struct UserId(u64);
struct OrgId(u64);

The newtype pattern is the operator’s way to brand identifiers without paying for an enum or trait object.

References#

  • Structs for the newtype pattern.

  • Generics for type parameters in aliases.