Primitive Data Types

Rust's primitive data types work slightly differently to other imperative languages like Python and C.

Rust is statically typed, but the type can be inferred at compile-time, negating the need to specify the type in some cases:


    

Integers require a specification of their bit count, as well as whether they are signed or unsigned:

A defined integer variable that isn't specified with a size or signature (like the first example on this page) will default to i32.

There also exists integer data types that are based on the CPU architecture of the machine executing the code: isize and usize. For example, on a 32-bit architecture, an isize variable would have the same bit count as an i32 variable.

Data types can't always be inferred, such as when the built-in into() method is used to convert a variable of one type to another:

error[E0283]: type annotations needed
|
3 | let y = x.into();
| type must be known at this point
|
= note: cannot satisfy `_: From<&str>`
= note: required for `&str` to implement `Into<_>`
help: consider giving `y` an explicit type
|
3 | let y: /* Type */ = x.into();

Since there's no information on what type variable y is, the compiler doesn't know how to convert to it from a string variable x.

For trivial problems, such as type mismatches or unclear typing, the Rust compiler and runtime can print direct, contextual suggestions for how to fix the error!

Floating-point numbers can only be two possible sizes in the stable release of Rust:

There are also f16 and f128 types, but these are currently only available in nightly (experimental) versions of the language.

Exercise:
Fix the typing error with the following code:


    

There is no "fsize" data type in Rust, but if no type is specified for a float, the compiler will default to f64:


    

Alternatively, for type annotation, the type of a numerical variable can be specified in its value:

An underscore can be optionally added, for clarity purposes.

Similar annotations exist for other types of numeral, like different number bases:

Booleans in Rust are lower-case, and require very little type annotation:


    

Expressions involving comparison of numerical values are also evaluated, and assigned as, bools:

Variable num isn't zero, so variable is_zero equates to false, with no annotation explicitly needed.


    

Characters in Rust are representations of Unicode, and accept all kinds of different characters and emoticons:


    

There are two string types in Rust:

Aside from having different mutability, these two types behave very differently from each other, and this difference will be fully explained in later chapters.