Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 132 ยท Variables and Types

Type Aliases, the Never Type and Inference

Learn Rust type aliases, the never type ! in panic, loop and return, how type inference works, the turbofish ::<>, Default::default() and the basics of size_of and alignment.

This lesson collects four small but important ideas about Rust's type system. A type alias gives a long type a short name. The never type ! is the type of expressions that do not finish, such as panic!. Type inference is how the compiler works out types you did not write, and the turbofish ::<> is how you help it when it cannot. We finish with Default::default() and a first look at how big values are in memory with size_of and alignment.

None of these is difficult, but together they explain a lot of what you see in real Rust code and in compiler errors. Everything here builds on scalar types, tuples and strings.

Type aliases

A type alias is a new name for an existing type, declared with type. It does not create a new type: the alias and the original are completely interchangeable.

Rust Type aliases

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.

Aliases shorten long types and document intent (Meters says more than f64). Because an alias is not a distinct type, it gives no safety: you can pass a Seconds where Meters is expected if both are f64. When you want the compiler to keep two things apart, use a newtype, a tuple struct such as struct Meters(f64);, which structs and advanced traits cover.

The most famous use of aliases is the Result alias. std::io::Result<T> is defined as Result<T, std::io::Error>, and libraries commonly define their own to avoid repeating the error type:

Rust A Result alias for a library

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.

Aliases may also be generic (type Pair<T> = (T, T);) and appear inside impl blocks and traits as associated types, which you will see in associated types.

Aliases are good for long, repeated types like Box<dyn Fn(i32) -> i32 + Send>. Do not hide important distinctions behind an alias. If a reader needs to know that something is a HashMap<String, Vec<u32>>, writing the type out can be clearer than inventing a name.

The never type !

Some expressions never produce a value because they never finish normally: they panic, loop forever, return from the function or exit the process. Rust gives these the special type !, read as never. It has no values at all.

Here are the four common producers:

Rust Expressions of type !

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.

A third producer is a loop without break, as in fn serve() -> ! { loop { handle_next_request(); } }, the shape of a server's main loop.

A function declared -> ! is called a diverging function. The compiler checks that its body really cannot return. panic!, unreachable!, todo!, unimplemented!, std::process::exit, loop {} without break, and the keywords return, break and continue are all expressions of type !.

Why ! is useful: it fits everywhere

The never type can be converted to any type. That sounds odd, but it is logical: since the expression never produces a value, there is no value of the wrong type to worry about. This is what makes the following ordinary code type-check:

Rust Never coerces to every type

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.

In the first match, one arm is an i32 and the other is continue. A match needs all its arms to have the same type, so how does it compile? continue has type !, which converts to i32, so the arms agree. The same trick makes let Some(x) = opt else { return }; and x.unwrap_or_else(|| panic!(...)) work.

A reminder from the loops lesson: loop has type ! unless it contains a break, and with break value; its type is the type of the value.

The never type also shows up in generics. Result<T, Infallible> (from std::convert::Infallible) is an error type with no values, used when an operation cannot fail, and the compiler can reason that the Err side is unreachable. Using ! itself as a type name in a struct or generic argument is still unstable; stick to function return types, which are stable.

Type inference

Rust is statically typed: every value has a type known at compile time. But you rarely write the types of local variables, because the compiler infers them from how the values are used. Inference is not "dynamic typing": the types are fixed, you just did not spell them.

Rust Inference at work

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.

The rules to remember:

  • A bare integer literal with no other information becomes i32; a float literal becomes f64.
  • Information can arrive later. Vec::new() leaves the element type open until push(7u8) fixes it. For e, the compiler first sees 200 and keeps the type open; the later let f: u8 = e makes it u8 (and 200 fits).
  • Inference works within a function. Function signatures, struct fields and consts must be written out, which keeps the interface of every function visible and prevents inference from spreading changes across modules.
  • Closures are the exception: their parameter and return types are inferred, fixed by first use.

If the compiler cannot decide, it asks you. This is the error message you will see most often when a type is missing:

Rust Not enough information (fails on purpose)

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.

The compiler answers with error[E0282]: type annotations needed for `Vec<_>` , and points at the line. Nothing ever pushes an element into items, so there is no way to know what it holds. The fix is to annotate: let items: Vec<i32> = Vec::new();.

The turbofish ::<>

Sometimes the type you want comes from the result of a call, and nothing else pins it down. A classic is parse: it can produce an i32, an f64, a bool, anything that implements FromStr. You tell it which in one of two ways: annotate the variable, or put the type directly on the call using the turbofish ::<Type>.

Rust Two ways to choose a type

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.

The name comes from the shape ::<>, which looks like a fish. Why the extra ::? Without it, parse<f64>() would look like the comparison operators < and >. You can also put the type on the generic type itself: Vec::<i32>::new() is the same as let v: Vec<i32> = Vec::new();. You can use _ for parts the compiler can work out: collect::<Vec<_>>() says "a Vec, element type inferred".

unwrap() here keeps the demo short, because all inputs are known to be valid. In real programs, handle the error (see Result).

Default::default()

Many types have a sensible "empty" or zero value, captured by the Default trait. Default::default() produces it, and inference decides which type is meant:

Rust Default values

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.

Numbers default to 0, bool to false, char to '\0', String, Vec and other collections to empty, Option to None, and tuples and arrays to the default of each element. With #[derive(Default)] your own struct gets the default of every field. The struct update syntax ..Default::default() fills in the rest, which is a common way to write constructors with many optional settings (structs shows it in depth).

A first look at size_of and alignment

Every type has a size (bytes it occupies) and an alignment (the address multiple it must start at). std::mem::size_of::<T>() and align_of::<T>() report them. Note that they use the turbofish, because there is no value to infer from.

Rust Sizes and alignment

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.

On the 64-bit sandbox, a reference to a sized type is 8 bytes (one pointer), but &str is 16: a pointer and a length. String and Vec<u8> are 24 bytes: pointer, capacity and length. These three words are on the stack; the text itself lives on the heap.

The struct Padded has fields of 1, 4 and 1 bytes (6 bytes of data), yet its size is 8, not 6. The compiler reorders fields to reduce padding, but it still has to round the total size up to a multiple of the largest alignment (4). Memory layout digs into repr(C), padding and the niche optimization. For now, remember that sizes are not always the sum of the parts, and that you can ask the compiler instead of guessing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After type Id = u32;, can you pass a value of type Id to a function that takes u32?

    A type alias does not create a new type. Id and u32 are interchangeable. Use a newtype struct if you need the compiler to tell them apart.
  2. 2. What is the type of panic!("boom")?

    panic! never completes normally, so its type is the never type !, which can be converted to any other type.
  3. 3. Why does let n: i32 = match s.parse() { Ok(v) => v, Err(_) => continue }; compile?

    All arms of a match must agree on a type. The continue expression has type ! and coerces to i32, so the arms agree.
  4. 4. What is the idiomatic way to pick the target type of parse without declaring a variable?

    The turbofish ::<Type> goes right after the method name. The leading :: is required so the compiler does not read the angle brackets as comparison operators.
  5. 5. A struct has fields of 1, 4 and 1 byte. What is size_of likely to report?

    The size is rounded up to a multiple of the struct's alignment (4 here), so six bytes of data become eight bytes.

Summary

  • type Name = ExistingType; gives a type another name. It creates no new type and offers no extra safety; use a newtype for that.
  • ! is the never type: the type of panic!, loop {}, return, break, continue and process::exit. It converts to any type, which is why match arms ending in continue or panic! compile.
  • Rust infers local variable types from usage, with i32 and f64 as literal defaults. Function signatures must be explicit.
  • When inference lacks information (E0282), annotate the variable or use the turbofish: parse::<f64>(), collect::<Vec<_>>().
  • Default::default() yields the zero or empty value of a type; derive Default on structs and use ..Default::default() to fill in the rest.
  • size_of::<T>() and align_of::<T>() report memory size and alignment; struct sizes include padding.

Next: Operators