Type

A type is a classification of values. Values of the same type have a similar meaning and purpose, and support the same operations. Values of different types can have the same memory representation – for example, both  and   can be represented by a zero, but because they are different types, the zero has a different meaning.

In Rust, types are enforced at compile time to prevent logic errors. However, since memory safety invariants are encoded in the type system, it also prevents memory safety bugs.

Types in Rust can be divided into:


 * Primitive types
 * Structs
 * Enums
 * Unions
 * Trait objects
 * Opaque types

Types can be generic. Generic types are sometimes called type constructors. For example,  is generic over. By substituting  with a type, new types such as   or   can be created.

Traits aren't types, but they categorize types with certain properties or functionality.

Type inference
Types of parameters and the return type of functions need to be specified explicitly. In other places, types can often be automatically inferred.

The compiler does this by giving values whose type isn't known an  type placeholder. Then the surrounding context is used to replace the type placeholders with actual types.

Example
Let's look at an example where a lot of type inference takes place, and see how the compiler approaches it: We don't know the type of, but we know that it implements the  trait. returns, which implements.

Since the  is , this tells the compiler that   in line 5 is an. Since  implements, Rust also infers the type   for the   literal. The return type is, which also happens to be.

accepts a closure and returns a type which implements. The  of the iterator is the return type of the closure.

returns a generic type  that implements. The compiler knows that the return type must be a, so it looks for implementations of  for  , and it finds. This means that the type in the  is the same type as , so Rust correctly infers the type   for.