Home About Me

Rust's Primitive Types and the Details Behind Their Sizes

Rust divides its primitive data types into several families. The choice of type affects how much memory a value uses, which values it can represent, and how the compiler treats operations on it.

Integer types

Integers come in signed and unsigned forms, and in several bit widths. The type name combines signedness with size: for example, i32 is a signed 32-bit integer, while u32 is unsigned.

<table> <thead> <tr> <th>Bit width</th> <th>Signed</th> <th>Unsigned</th> </tr> </thead> <tbody> <tr> <td>8-bit</td> <td>i8</td> <td>u8</td> </tr> <tr> <td>16-bit</td> <td>i16</td> <td>u16</td> </tr> <tr> <td>32-bit</td> <td>i32</td> <td>u32</td> </tr> <tr> <td>64-bit</td> <td>i64</td> <td>u64</td> </tr> <tr> <td>128-bit</td> <td>i128</td> <td>u128</td> </tr> <tr> <td>architecture-dependent</td> <td>isize</td> <td>usize</td> </tr> </tbody> </table>

Unsigned integers hold only zero and positive values. Signed integers can hold positive values, negative values, and zero. The isize and usize types depend on the CPU the program runs on: on a 32-bit CPU they are 32 bits, and on a 64-bit CPU they are 64 bits.

Floating-point types

Floating-point numbers carry a decimal point. Rust has two primitive floating-point types: f32 and f64, at 32 and 64 bits respectively.

<table> <thead> <tr> <th>Bit width</th> <th>Type</th> </tr> </thead> <tbody> <tr> <td>32-bit</td> <td>f32</td> </tr> <tr> <td>64-bit</td> <td>f64</td> </tr> </tbody> </table>

The default is f64. On modern CPUs its speed is close to that of f32, and it offers higher precision.

Boolean type

Rust's boolean type has two possible values: true and false. A boolean occupies one byte of memory.

Character type

Rust's character type is more than ASCII. A char can represent any Unicode scalar value, and it occupies four bytes.

Unit type

The unit type is (). Its only value is also (). It resembles Unit in Kotlin. A function with no return value produces ().