Rust Reference ยท Keywords and Statements
The type keyword
Reference for Rust type: type aliases, generic aliases like io::Result, associated types in traits and impls, and how aliases differ from newtypes.
type introduces a new name for a type. A type alias does not create a new type: the alias and the original are completely interchangeable. Aliases shorten long types and let a library fix one parameter, as std::io::Result<T> does for the error type.
Inside a trait, type declares an associated type, a placeholder that each implementation fills in. Iterator::Item is the best-known example.
type Grid = Vec<Vec<u8>>;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
[pub] type Alias<generics> = Type; // alias type Name [: Bounds]; // associated type in a trait type Name = Type; // associated type in an impl
| Part | Description |
|---|---|
| Alias generics | Aliases may be generic: type Pair<T> = (T, T);. Bounds on alias parameters are not enforced. |
| Associated type | Declared in a trait, optionally with bounds (type Item: Debug;). Referred to as Self::Item or <T as Trait>::Item. |
| Generic associated types (GATs) | type Item<'a> where Self: 'a; lets an associated type take lifetime or type parameters (stable since 1.65). |
Usage notes
- Aliases are transparent.
type Meters = f64;does not stop you from addingMetersto any otherf64. Use a newtype (struct Meters(f64);) when you want the compiler to keep them apart. - Aliases cannot add trait impls or inherent methods to the original type; they are only names.
- Associated types versus generics:
Iteratorhas oneItemper implementing type, so users writeI::Iteminstead of passing a second type parameter. - Common aliases:
std::io::Result<T>,std::fmt::Result, and crate-wideResult<T>aliases are everywhere in the ecosystem. impl Traitin an alias (type Evens = impl Iterator<...>) is unstable; use it directly in function signatures instead.- Type alias in
use:use std::collections::HashMap as Map;renames an import, which is a different feature fromtype.
Related
trait,impl,struct,use- Lessons: Associated types, Type aliases and never