W3cubDocs

/Rust

Keyword type

Define an alias for an existing type.

The syntax is type Name = ExistingType;.

Examples

type does not create a new type:

type Meters = u32;
type Kilograms = u32;

let m: Meters = 3;
let k: Kilograms = 3;

assert_eq!(m, k);

In traits, type is used to declare an associated type:

trait Iterator {
    // associated type declaration
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

struct Once<T>(Option<T>);

impl<T> Iterator for Once<T> {
    // associated type definition
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.take()
    }
}

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/keyword.type.html