Sub topic 7
Integer types and literals
This chapter assumes you can declare bindings with let, use mut, and read a basic compiler error. It covers the integer types Rust offers, how the compiler picks one, and how to write integer values in source code. Overflow behavior and conversions between types get their own chapters, so they appear here only where needed.
The integer family
Rust has twelve built-in integer types. Each one has a fixed size in bits, and each is either signed or unsigned. Signed types (i8, i16, i32, i64, i128, isize) can hold negative values and are stored in two's complement. Unsigned types (u8, u16, u32, u64, u128, usize) hold zero and positive values only.
An n-bit signed type holds -2^(n-1) through 2^(n-1) - 1. An n-bit unsigned type holds 0 through 2^n - 1.
| Bits | Signed | Signed range | Unsigned | Unsigned range |
|---|---|---|---|---|
| 8 | `i8` | -128 to 127 | `u8` | 0 to 255 |
| 16 | `i16` | -32,768 to 32,767 | `u16` | 0 to 65,535 |
| 32 | `i32` | -2,147,483,648 to 2,147,483,647 | `u32` | 0 to 4,294,967,295 |
| 64 | `i64` | about ±9.2 × 10^18 | `u64` | 0 to 18,446,744,073,709,551,615 |
| 128 | `i128` | about ±1.7 × 10^38 | `u128` | 0 to about 3.4 × 10^38 |
| pointer width | `isize` | depends on target | `usize` | depends on target |
You don't need to memorize the ranges. Every integer type has the associated constants MIN and MAX, plus BITS:
fn main() {
println!("{} {}", i8::MIN, i8::MAX);
println!("{} {}", u8::MIN, u8::MAX);
println!("{} {}", i32::MIN, i32::MAX);
println!("{}", u64::MAX);
println!("{} bits", i128::BITS);
}This prints -128 127, 0 255, -2147483648 2147483647, 18446744073709551615, and 128 bits.
Note that the signed range is asymmetric. i8 has one more negative value than positive values, so i8::MIN has no positive counterpart. This matters later when you negate or take the absolute value of a minimum.
How the compiler picks a type
Rust is statically typed, so every integer has exactly one type at compile time. An integer literal such as 42 has no type of its own. The compiler treats it as "some integer" and resolves it in this order:
- A suffix on the literal, such as
42u8. - An annotation on the binding, such as
let b: u64 = 42;. - How the value is used elsewhere, such as being passed to a function that takes
u8. - If nothing constrains it, the fallback type
i32.
use std::mem::size_of_val;
fn main() {
let a = 42;
let b: u64 = 42;
let c = 42u8;
println!("{} {} {}", size_of_val(&a), size_of_val(&b), size_of_val(&c));
}The output is 4 8 1, the sizes in bytes of i32, u64, and u8.
Step 3 can reach backward through your code:
fn main() {
let x = 200;
let y: u8 = x;
println!("{y}");
}Here x has no annotation, but assigning it to a u8 binding makes x a u8 too. If you changed 200 to 300, the program would not compile. A literal that doesn't fit its resolved type triggers the overflowing_literals lint, which is deny-by-default. The message reads literal out of range for u8.
Integer literals
You can write the same number in several bases. Underscores are ignored and exist only to make long numbers readable.
| Form | Example | Value |
|---|---|---|
| Decimal | `98_222` | 98222 |
| Hexadecimal | `0xff` | 255 |
| Octal | `0o77` | 63 |
| Binary | `0b1111_0000` | 240 |
| Byte | `b'A'` | 65, of type `u8` |
A type suffix can be attached to any of these forms. An underscore before the suffix is allowed.
fn main() {
let dec = 98_222;
let hex = 0xff;
let oct = 0o77;
let bin = 0b1111_0000;
let byte = b'A';
let typed = 57u8;
let also_typed = 1_000_i64;
println!("{dec} {hex} {oct} {bin} {byte} {typed} {also_typed}");
}This prints 98222 255 63 240 65 57 1000. Only byte is guaranteed to be a u8. The others are i32 here because nothing else constrains them.
The reverse direction uses format specifiers. x and X give hex, o gives octal, b gives binary, # adds the prefix, and 08 pads with zeros to width 8:
fn main() {
let n = 255u8;
println!("{n:x} {n:X} {n:#b} {n:o} {n:08b}");
}The output is ff FF 0b11111111 377 11111111.
Literals and method calls
If a literal has no resolved type yet, you cannot call a method on it. This fails with error E0689, "can't call method pow on ambiguous numeric type {integer}":
fn main() {
// let n = 2.pow(10); // error[E0689]
let a = 2_i32.pow(10);
let b: i32 = 2;
println!("{a} {}", b.pow(10));
}Add a suffix or bind the value to an annotated variable. Both forms print 1024.
`usize` and `isize`
usize and isize have the width of a pointer on the target platform: 64 bits on a 64-bit machine, 32 bits on a 32-bit one. Rust uses usize wherever a value describes memory: the length of a collection, an index, or an offset. Indexing an array or slice requires a usize:
fn main() {
let data = [10, 20, 30];
let i: usize = 1;
println!("{} {}", data[i], data.len());
// let j: i32 = 1;
// data[j]; // error: the type `[i32]` cannot be indexed by `i32`
}This strictness is deliberate. An index can never be negative, and its range must match the platform's address space.
Do not use usize as a general-purpose "big number" type. Its size varies by platform, so data that must have a stable size, such as file formats, network protocols, or stored IDs, should use a fixed-width type like u32 or u64.
Arithmetic rules
Both operands of an arithmetic operator must have the same type. Rust does not widen automatically, so adding an i32 to an i64 is a compile error (E0308, mismatched types). You have to convert one side yourself. A later chapter covers how.
Integer division truncates toward zero. The % operator returns a remainder that takes the sign of the left operand. If you need a mathematical modulo that is never negative, use rem_euclid.
fn main() {
println!("{}", -7 / 2);
println!("{}", -7 % 2);
println!("{}", (-7i32).rem_euclid(2));
println!("{}", (-7i32).div_euclid(2));
println!("{}", 7u32.abs_diff(10));
println!("{}", 2_i32.pow(10));
}The output is -3, -1, 1, -4, 3, and 1024. Dividing or taking a remainder by zero panics in every build profile. abs_diff is worth knowing for unsigned values, because 7u32 - 10 would underflow, while abs_diff returns the distance safely.
Useful built-in methods
Integer types carry many inherent methods. A few you will use often:
fn main() {
println!("{}", 0b1011_0000u8.count_ones());
println!("{}", 1u32.leading_zeros());
println!("{}", 1u32 << 4);
println!("{:?}", i64::from_str_radix("ff", 16));
println!("{}", 10.min(3));
}The output is 3, 31, 16, Ok(255), and 3. The last line works because min is a method of the Ord trait, and the literals default to i32. from_str_radix parses text in any base from 2 to 36 and returns a Result, because the input can be invalid.
The bit-shift operators << and >> and the bitwise operators &, |, ^, and ! work on all integer types. Shifting by an amount greater than or equal to the type's bit width counts as overflow. It panics in debug builds, which the overflow chapter explains.
Choosing a type
Start from the default and move away only for a reason:
- Use
i32when nothing else applies. It is the compiler's own fallback and is fast on all common targets. - Use
usizefor indexes, lengths, and counts of items in memory. - Use
u8for raw bytes and ASCII-range data. - Use
u64ori64when values can exceed about two billion, such as timestamps in milliseconds, file sizes, and database IDs. - Use
u32oru16when a format or API specifies it. - Use
i128oru128for very large intermediate results. They are slower than 64-bit types on most hardware.
Choosing a smaller type only to save memory rarely helps for single values. It matters when you store millions of them in an array or a Vec.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `literal out of range for u8` | The literal does not fit the resolved type | Use a wider type or a smaller value |
| `mismatched types` on `a + b` | Operands have different integer types | Convert one operand explicitly |
| `cannot be indexed by i32` | Index is not a `usize` | Declare the index as `usize` |
| `can't call method on ambiguous numeric type` | The literal has no type yet | Add a suffix or an annotation |
Exercise
What are the types of a, b, and c in this program, and why? Does it compile?
fn main() {
let a = 1_000;
let b = 7;
let c: u8 = b;
println!("{a} {b} {c}");
}
Show answer
a is i32, because nothing constrains it and i32 is the fallback. b is u8, because it is assigned to c: u8, so inference resolves the literal 7 as a u8. c is u8 by annotation. The program compiles and prints 1000 7 7.
Exercise
Write a program that stores the byte value 0b1010_1010 in a u8 and prints it in decimal, hexadecimal, and zero-padded 8-digit binary. State the expected output.
Show answer
fn main() {
let n = 0b1010_1010u8;
println!("{n} {n:x} {n:08b}");
}
The output is 170 aa 10101010.