The egg rack in the kitchen of Rusdi's Pancake Stall only fits 255 eggs. The cash drawer holds millions of cents, the syrup jug has decimal marks, and the OPEN/CLOSED sign has only two sides. Each container is picked to suit what goes in it, and whatever is more than the container holds spills.
In Rust, each of those containers is a type, and what is in it is the value. The egg rack and the cash drawer are like the types for whole numbers, a small one and a big one. The syrup jug is like a type for decimal numbers, and the OPEN/CLOSED sign is like the type for true/false. Every value has a type, which sets what kind of data it is and how big it is in memory. Types are settled at compile time. When you don't write a type, the compiler guesses it from the value.
Whole numbers (integers)
| Type | Can be negative? | Range |
|---|---|---|
u8 |
no | 0 to 255 |
i32 |
yes | -2,147,483,648 to 2,147,483,647 |
u32 |
no | 0 to 4,294,967,295 |
i64 |
yes | about ±9.2 quintillion |
The letter i means signed (may be negative), u means unsigned (never negative), and the number is how many bits it has. A bit is the smallest unit of memory: the more bits, the wider the range of numbers. There are also i8, i16, i128, u16, u64, u128, and usize (used for lengths and positions). If you don't write the type, a whole number becomes an i32.
This code makes three whole-number variables, then prints them and calculates a division:
fn main() {
let portions = 2;
let sweet_price: u32 = 3_200;
let egg_stock: u8 = 250;
println!("{} {} {}", portions, sweet_price, egg_stock);
println!("{} {}", 3200 / 3, 3200 % 3);
}
The output:
2 3200 250
1066 2
: u32after the variable's name is how you write the type yourself.portionshas no type written, so Rust guessesi32.3_200is the same as3200: the price in cents, $32.00. The underscore is only there to make it easier to read.- Each
{}is filled by the values after the comma, in order. - Dividing two integers drops the fraction:
3200 / 3is1066, not 1066.67.%gives the remainder of the division:2.
Decimals, bool, char and text
This code makes one variable for each of the other types:
fn main() {
let rating: f64 = 4.8;
let is_open: bool = true;
let menu_code: char = 'T';
println!("{} {} {}", rating, is_open, menu_code);
println!("{} {}", 7.0 / 2.0, 42.0);
println!("{} {}", "Crêpe".len(), "Crêpe".chars().count());
}
The output:
4.8 true T
3.5 42
6 5
f64is the type for decimal numbers. When the type isn't written, a number with a point is guessed as anf64. Decimals are written with a point:4.8, not4,8. Note that{}prints42.0as42.bool(true/false) is onlytrueorfalse.charis one character in single quotes'T', and always takes 4 bytes of memory (1 byte = 8 bits).- Text in double quotes has the type
&str. Text is stored as UTF-8, a way of storing letters as bytes: a plain letter is 1 byte, a letter such asêis 2 bytes. So"Crêpe".len()(the number of bytes) is6, while.chars().count()(the number of characters) is5. Both are methods: commands you call with a dot after a value.
Converting types: as and parse
Rust never changes a type quietly. Say there are portions: u32 and rating: f64. The compiler refuses portions * rating with cannot multiply `u32` by `f64` . You have to change the type yourself, as in this code:
fn main() {
let portions: u32 = 2;
let portions_f64 = portions as f64;
println!("{}", portions_f64 * 4.8);
let note = "3800";
let price: u32 = note.parse().unwrap();
println!("{}", price * 2);
let rating = 4.8;
let stars = rating as i32;
println!("{}", stars);
}
The output:
9.6
7600
4
asturns one number type into another.portions as f64becomes2.0. Printed on its own,2.0shows as2.- From a decimal to an integer,
ascuts off the fraction; it doesn't round:4.8 as i32is4,3.7 as i32is3. .parse()turns text into a number. The target type has to be clear, which is why the code sayslet price: u32. Without that type, the compiler refuses withtype annotations needed(the type must be written)..unwrap()takes out the number that.parse()made. If the text isn't a number, say"two", the program stops while running withcalled `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }.
Numbers that overflow
Back to the egg rack, which only fits 255 eggs. The stock is stored as a u8 holding 250. Then a delivery of 10 eggs arrives and is added. The size of the delivery is read from the text of the delivery note with .parse(), so its value is only known while the program runs. Before you look at what cargo run prints, guess: 260, 4, or does the program stop with an error?
fn main() {
let egg_stock: u8 = 250;
println!("Egg stock: {}", egg_stock);
let delivery: u8 = "10".parse().unwrap();
let new_stock = egg_stock + delivery;
println!("Egg stock: {}", new_stock);
}
This is what cargo run prints:
$ cargo run
Compiling stall v0.1.0 (/home/you/stall)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.51s
Running `target/debug/stall`
Egg stock: 250
thread 'main' (23111499) panicked at src/main.rs:5:21:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
250 + 10 = 260, but a u8 only goes up to 255. This is an overflow: the result doesn't fit in its type, like eggs spilling from the rack. In an ordinary (debug) build, the one cargo run makes, Rust checks for overflow and the program panics: it stops while running. The message is attempt to add with overflow, at src/main.rs line 5, column 21. The line Egg stock: 250 did print, because the panic happens at runtime, not at compile time. The number in brackets after 'main' is the thread number (a thread is one line of work in the program), and it is different on every run.
This is what the same program prints with cargo run --release:
$ cargo run --release
Compiling stall v0.1.0 (/home/you/stall)
Finished `release` profile [optimized] target(s) in 0.68s
Running `target/release/stall`
Egg stock: 250
Egg stock: 4
In a --release build the overflow check is off, for speed. The number wraps around: after 255 it goes back to 0. A u8 has 256 values (0 to 255), so 260 becomes 260 - 256 = 4. The program keeps running with the wrong stock. So the answer depends on the build: a panic or 4, but never 260. If both numbers are written straight into the code (let delivery: u8 = 10;), the compiler already sees the result at compile time. It refuses the code with this arithmetic operation will overflow. The fix is a container big enough: a u32 holds over 4 billion.
When the number really can overflow, Rust has methods that give the same result in both kinds of build:
fn main() {
let egg_stock: u8 = 250;
let delivery: u8 = "10".parse().unwrap();
println!("{:?}", egg_stock.checked_add(delivery));
println!("{}", egg_stock.saturating_add(delivery));
println!("{}", egg_stock.wrapping_add(delivery));
}
The output:
None
255
4
{:?} in the first println! prints a value that {} can't print, such as None. When to pick which:
| Way | 250 + 10 | When to pick it |
|---|---|---|
A bigger type (u32) |
260 | The default: the stock really can go past 255. |
checked_add |
None |
You want to know when the result overflows, then refuse it or report it. None means "no result", and the lesson on Option shows how to read it. |
saturating_add |
255 | Stopping at the upper limit is enough, for example a rack that really holds only 255. |
wrapping_add |
4 | Wrapping around is what you want, like the hands of a clock. |
There are also versions for subtraction and multiplication, such as checked_sub and checked_mul.
Tuples and arrays
Tuples and arrays keep several values in one variable:
fn main() {
let order: (&str, u32, bool) = ("Egg Pancake", 2, true);
println!("{} x{}", order.0, order.1);
let prices: [u32; 3] = [3200, 3800, 500];
println!("Iced Tea: {}", prices[2]);
println!("Menu items: {}", prices.len());
}
The output:
Egg Pancake x2
Iced Tea: 500
Menu items: 3
- A tuple groups values inside round brackets. Their types may differ, but the number of values is fixed. You read them with a dot and a position number starting from 0:
order.0,order.1,order.2. - An array holds values of the same type inside square brackets, and the number of values is fixed:
[u32; 3]means threeu32s. You read them withprices[0]toprices[2], andprices.len()gives how many there are. A number past the end, such asprices[3], is refused.
⚠️ Types that make a sum get refused or come out wrong
- Mixing types in a sum. A
u32times anf64is refused. Convert one of them withas. - Thinking
asrounds.3.7 as i32is3. The fraction is cut off. parsewith no target type. Write the type on the variable:let number: i32 = text.parse().unwrap();.- Mixed-up quotes.
let code: char = "T";is refused withexpected `char`, found `&str`. Achartakes single quotes. - A container too small. A
u8for stock that can go past 255 means a panic in debug and a wrong number in release.
TL;DR: Every value has a type (the kind of value) settled at compile time. With no type written, a whole number becomes an i32 (signed: may be negative, 32 bits). A u8 only holds 0 to 255, a u32 0 to 4.29 billion. A decimal number is guessed as an f64, a bool is only true/false, a char is one character in single quotes (4 bytes), and text in double quotes is a &str. On text, .len() counts UTF-8 bytes, not letters. Integer (whole-number) division drops the fraction. A type never changes by itself: as converts between numbers and cuts off decimals (3.7 as i32 = 3), and .parse().unwrap() turns text into a number of the type you write. An overflow (a result that doesn't fit in its type) makes the program panic, which means stop while running, in a debug build (attempt to add with overflow). In a release build, the number wraps around silently. A tuple (values of different types in round brackets) is read with .0, .1, an array (values of one type in square brackets) with [0], both starting from 0.
⚡ i, u and the bit count
Write:
let portions = 2;
let sweet_price: u32 = 3_200;
let egg_stock: u8 = 250;
Meaning: : u32 after a variable's name is a type you write yourself. i means signed (may be negative), u unsigned (never negative), and the number is the bit count: the more bits, the bigger the numbers that fit. portions has no type written, so Rust guesses i32. A u8 only holds 0 to 255. 3_200 is the same as 3200.
⚡ as cuts, parse reads text
Write:
let note = "3800";
let price: u32 = note.parse().unwrap();
let stars = 4.8 as i32; // 4
Meaning: A type never changes by itself. .parse() turns the text "3800" into a number of type u32 (the type written in the code), and .unwrap() takes the number out. as turns one number type into another and cuts off decimals; it doesn't round: 4.8 as i32 is 4.
⚡ The egg rack overflows
Guess first: an egg stock of type u8 holds 250, then a delivery of 10 eggs is added. Is the result 260?
Never 260. An ordinary build (cargo run) checks the result and panics, which means it stops while running, with attempt to add with overflow. A --release build doesn't check, so the number wraps around: after 255 it goes back to 0, and the result is 4.
Meaning: A result that doesn't fit in its type is called an overflow. The fix is a type big enough, such as a u32.
⚡ Tuples and arrays
Write:
let order: (&str, u32, bool) = ("Egg Pancake", 2, true);
let prices: [u32; 3] = [3200, 3800, 500];
println!("Iced Tea: {}", prices[2]);
Meaning: A tuple groups values inside round brackets, and their types may differ: order holds text (&str), a number (u32) and a true/false value (bool). An array keeps values inside square brackets, and they must all have the same type: [u32; 3] means three u32s. A tuple is read with .0, .1, an array with [0], both starting from 0. So prices[2] is the third value, 500.