Rust Integer Types
An integer type is a Rust type for a whole number. Rust has a family of integer types, not one type.
Read the range from the type
Every integer type carries its smallest and largest values. Just ask for them:
println!("u8: {} to {}", u8::MIN, u8::MAX);Signed takes a minus, unsigned does not
An i type holds negative values too. A u type holds zero and up only:
let temp: i8 = -12;
let count: u8 = 200;
println!("{} {}", temp, count);Unsigned means no minus sign
An unsigned type can never hold a negative value, so even writing the minus sign is refused. This program does not compile: error E0600 says unsigned values cannot be negated.
let x: u32 = -200;
println!("{}", x);Underscores make big numbers readable
Group the digits of a long number with underscores. Rust ignores them — they are purely for your eyes:
let crowd = 1_000_000;
println!("{}", crowd);Other bases, and a byte literal
0x starts a hex number, 0o an octal one and 0b a binary one. A byte literal like b'A' is the number code of a character:
println!("{} {} {}", 0xff, 0o77, 0b1010);
println!("A code = {}", b'A');Example
fn main() {
let small: u8 = 255;
let big: i64 = 9_000_000_000;
let mask: u8 = 0b1111_0000;
let letter_code: u8 = b'A';
let pos: usize = 3;
println!("{} {} {} {} {}", small, big, mask, letter_code, pos);
println!("u8 range: {} to {}", u8::MIN, u8::MAX);
}Key points
- The number in the name is the size in bits.
- A u8 holds 0 to 255.
- An i8 holds -128 to 127.
- isize and usize are machine-sized: 64-bit on most computers today
- Use usize for positions and counts.
- A Vec length, for example, is a usize.
- It has appeared as a return type.
- The right type is the size that fits the values.
In this example, five whole numbers show five corners of the family. small is a u8 at its very top, 255. big is an i64, large enough for nine billion. mask is written in binary: 0b1111_0000 is 240. letter_code uses a byte literal: b'A' is the number 65. pos is a usize, the type Rust uses for positions. The last line reads the range straight from the type itself: u8::MIN is 0 and u8::MAX is 255.
Note
Many languages have one integer type that quietly grows.
Rust makes you choose the range up front.
Then it guarantees values stay inside it.
Or it tells you loudly when they cannot.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What is the largest value a u8 can hold?