🎓 A1Learner
🔍
0 of 142 lessons completed

Rust Type Aliases

A type alias is a second name for a type that already exists. An alias does not create a new type.

A long type, written again and again

A tuple type written out in full repeats the same spelling at each use:

fn main() {
    let start: (i32, i32) = (0, 0);
    let end: (i32, i32) = (3, 4);
    println!("({}, {}) to ({}, {})", start.0, start.1, end.0, end.1);
}

Give a type a second name

The word type makes the alias. From then on, both names work:

type NanoSecond = u64;
let wait: NanoSecond = 5;
println!("wait = {}", wait);

An alias is not a new type

NanoSecond, Inch and u64 are exactly the same type. They are just three names. So their values mix freely. Rust happily adds them:

type NanoSecond = u64;
type Inch = u64;
let a: NanoSecond = 5;
let b: Inch = 2;
println!("sum = {}", a + b);

Shorten a long type

Use an alias to shorten a long type you write again and again, so code is quicker to read. Rust itself does the same. std::io::Result<T> is an alias for Result<T, std::io::Error>. The alias hides the error type you would otherwise repeat:

type Point = (i32, i32);
let p: Point = (3, 4);
println!("({}, {})", p.0, p.1);

Example

type NanoSecond = u64;
type Inch = u64;
type U64 = u64;
fn main() {
    let nanoseconds: NanoSecond = 5;
    let inches: Inch = 2;
    let plain: U64 = 10;
    println!("{} nanoseconds + {} inches = {}", nanoseconds, inches, nanoseconds + inches);
    println!("plain = {}", plain + nanoseconds);
}

Key points

  • Alias names use UpperCamelCase, like other type names.
  • A lower-case alias still works.
  • But the compiler warns about its name.
  • Built-in names like u64 are the exception.

In this example, three aliases all name the same type, u64. nanoseconds is 5 and inches is 2. Because an alias is only a name, Rust happily adds them: 5 + 2 = 7. The second line adds plain, written with the U64 alias, to nanoseconds and gets 15. Nothing checks the units — that freedom is exactly what an alias means, and exactly its limit.

Note

An alias gives no protection against mixing units.

Suppose adding nanoseconds to inches must be an error.

Then you need a new type in its own struct.

That struct is the newtype pattern.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

type Inch = u64; — what does Inch give you?