Part 01 · Rust Is Not Scary

Numbers, Text and Booleans

i32u64f64boolchar

The basic types, why Rust asks i32 or u64, and what happens when a number gets too big.

⏱ 9 min · Station 6 of 75

The story

A shop stores things in containers of fixed sizes: a matchbox, a jar, a sack, a drum. Nobody keeps a sack of rice in a matchbox, and nobody keeps three matches in a drum. You pick the container that fits what will go in it, and you think about the biggest amount it will ever need to hold.

Numbers in Rust work the same way. Every number lives in a container of a fixed size, its type, and Rust asks you to pick one. That is why you see u8, i32 and u64 everywhere. It feels fussy for a week, and then it saves you from the bugs that happen when a number quietly doesn't fit.

The idea

The basic types you'll use every day:

TypeWhat it holdsShop example
u8, u16, u32, u64whole numbers, unsigned (0 and up)stock count, order id, money in paisa
i8, i16, i32, i64whole numbers, integer with a sign (can be negative)a balance that can go below zero
f64 (and f32)numbers with a fraction, floating pointweight in kg, a rating like 4.5
booltrue or falsein stock or not
charone charactera grade like 'A', or '৳'

The number after the letter is the size in bits. More bits, bigger range:

u80 to 2558 bitsu160 to 65,53516 bitsu320 to about 4.3 billion32 bitsu640 to about 18 quintillion64 bits250 + 10260 does not fit in a u8: debug build panics, release build wraps to 4260pick a type big enough for every value it will ever hold
Each integer type is a box with a fixed size. 250 + 10 = 260 does not fit a u8, which only holds 0 to 255, but it fits a u16 easily.

If you don't write a type, Rust picks one: i32 for whole numbers and f64 for fractions. Most of the time it can also work the type out from how you use the value.

fn main() {
    let stock: u32 = 128; // can't be negative
    let balance: i64 = -2_500; // can be negative: a customer owes money
    let price_paisa: u64 = 42_000; // ৳420.00, money kept as whole paisa
    let weight_kg: f64 = 2.5; // a number with a fraction
    let in_stock: bool = stock > 0;
    let grade: char = 'A';

    println!("{stock} {balance} {price_paisa} {weight_kg} {in_stock} {grade}");
    println!("u8  holds 0 to {}", u8::MAX);
    println!("i32 holds {} to {}", i32::MIN, i32::MAX);
    println!("u64 holds 0 to {}", u64::MAX);
}
128 -2500 42000 2.5 true A
u8  holds 0 to 255
i32 holds -2147483648 to 2147483647
u64 holds 0 to 18446744073709551615

Two small tricks in there: _ inside a number is ignored, so 42_000 is easier to read than 42000, and u8::MAX gives you the biggest value a type can hold.

Money tip: store money as whole paisa in an integer (u64), not as taka in an f64. You'll see why in a minute.

Try it: when a number doesn't fit

A shelf of eggs is counted in a u8. There are 250, and a delivery brings 10 more. The 10 comes from text parsed at runtime, so the compiler can't see the number in advance:

fn main() {
    let mut eggs: u8 = 250;
    let delivery: u8 = "10".parse().expect("not a number"); // known only at runtime
    println!("eggs before: {eggs}");
    eggs += delivery;
    println!("eggs after: {eggs}");
}
Predict first

250 + 10 in a u8 (which holds 0 to 255). What does cargo run do?

eggs before: 250

thread 'main' (1690197) panicked at src/main.rs:5:5:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

A panic is Rust stopping the program on purpose because something is wrong, and telling you where (src/main.rs:5:5). Now the release build:

eggs before: 250
eggs after: 4

In release mode the check is gone for speed, and the number wraps around: 256 becomes 0, 257 becomes 1, ..., 260 becomes 4. Ten eggs arrived and the shelf now says 4.

So the lesson is: debug builds catch overflow while you test, but the real fix is choosing a type big enough. Use u32 for a stock count and the problem disappears. And when a number really can go past the limit, say what should happen with these methods:

fn main() {
    let eggs: u8 = 250;
    let delivery: u8 = 10;
    println!("checked:    {:?}", eggs.checked_add(delivery));
    println!("checked:    {:?}", eggs.checked_add(5));
    println!("saturating: {}", eggs.saturating_add(delivery));
    println!("wrapping:   {}", eggs.wrapping_add(delivery));

    let quantity: u32 = 3;
    let price: f64 = 84.5;
    println!("total:      {}", quantity as f64 * price);
    println!("7 / 2 = {}, 7.0 / 2.0 = {}", 7 / 2, 7.0 / 2.0);
    println!("0.1 + 0.2 = {}", 0.1 + 0.2);
}
checked:    None
checked:    Some(255)
saturating: 255
wrapping:   4
total:      253.5
7 / 2 = 3, 7.0 / 2.0 = 3.5
0.1 + 0.2 = 0.30000000000000004
  • checked_add gives an Option: None if it doesn't fit, Some(value) if it does. Same Option you met in Why Rust Feels Hard.
  • saturating_add stops at the maximum (255).
  • wrapping_add wraps around on purpose (4), useful for things like hash functions, never for money.
  • as converts between types: quantity as f64 turns the u32 into an f64 so it can be multiplied by a price.
  • Whole-number division drops the fraction: 7 / 2 is 3.
  • And 0.1 + 0.2 is not exactly 0.3. That is not a Rust bug: every language that uses standard floating point does this, because 0.1 can't be stored exactly in binary. It's why money goes in integers.

What the compiler says

When Rust can see the problem at compile time, it stops you before running anything:

fn main() {
    let eggs: u8 = 256;
    println!("{eggs}");
}
error: literal out of range for `u8`
 --> src/main.rs:2:20
  |
2 |     let eggs: u8 = 256;
  |                    ^^^
  |
  = note: the literal `256` does not fit into the type `u8` whose range is `0..=255`
  = note: `#[deny(overflowing_literals)]` on by default

error: could not compile `literal` (bin "literal") due to 1 previous error
  • error: literal out of range for `u8` : the number you typed (256) can never fit in a u8.
  • note: ... whose range is `0..=255` : it even tells you the range. 0..=255 means 0 to 255, including 255.
  • This one has no E number. It comes from a lint, a rule that checks your code, set to deny so it's an error, not a warning.

The other first-week surprise: Rust never mixes number types for you.

fn main() {
    let quantity: u32 = 3;
    let price: f64 = 84.5;
    let total = quantity * price;
    println!("{total}");
}
error[E0277]: cannot multiply `u32` by `f64`
 --> src/main.rs:4:26
  |
4 |     let total = quantity * price;
  |                          ^ no implementation for `u32 * f64`
  |
  = help: the trait `Mul<f64>` is not implemented for `u32`
  = help: the following other types implement trait `Mul<Rhs>`:
            `&u32` implements `Mul<u32>`
            `&u32` implements `Mul`
            `u32` implements `Mul<&u32>`
            `u32` implements `Mul<Duration>`
            `u32` implements `Mul`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `mixed` (bin "mixed") due to 1 previous error

cannot multiply `u32` by `f64` : in many languages 3 * 84.5 just works, because the language quietly converts one side. Rust won't guess, since a quiet conversion can lose precision or turn negative numbers into huge ones. You say exactly what you want with as: quantity as f64 * price, which is what the safe program above does. (The list of "other types" below the help line is noise for now; skip it.)

Under the hood

Why do fixed sizes exist at all? Because that's how the CPU works. A 64-bit CPU adds two u64 values in one instruction. The type tells the compiler exactly which instruction to use and exactly how many bytes each value takes: a u8 is 1 byte, a u32 4, a u64 8. A million stock counts as u32 take 4 MB; as u64, 8 MB.

Signed and unsigned use the same bits differently. A u8 uses all 8 bits for 0 to 255. An i8 uses one for the sign, so it holds -128 to 127. That's why i32::MIN above is -2147483648 but i32::MAX is only 2147483647: there is one more negative number than positive.

The overflow check in debug builds is real code the compiler adds after every +, - and *. In release builds it's removed, which is part of why release builds are faster. You can keep the checks in release too, with overflow-checks = true under [profile.release] in Cargo.toml, if correctness matters more than the last bit of speed.

Compared with other languages

The same overflow in Go, plus two things JavaScript and Python do differently:

package main

import "fmt"

func main() {
	var eggs uint8 = 250
	delivery := uint8(10)
	eggs += delivery
	fmt.Println("Go eggs after:", eggs)
}
console.log("JS:", 9007199254740993); // 2^53 + 1, an order id from a big system
console.log("JS:", 0.1 + 0.2);
print("Python:", 2**64 + 1)
print("Python:", 0.1 + 0.2)
Go eggs after: 4
JS: 9007199254740992
JS: 0.30000000000000004
Python: 18446744073709551617
Python: 0.30000000000000004
  • Go wraps silently, always. 250 + 10 is 4, no warning, debug or not.
  • JavaScript stores every number as a 64-bit float. Integers above 2^53 can't all be stored exactly, so the order id 9007199254740993 silently became ...992, a different order. This has bitten real systems that pass large ids through JSON.
  • Python integers grow as big as needed, so they never overflow. The price is speed and memory: every Python integer is an object.
  • And 0.1 + 0.2 is 0.30000000000000004 in all of them.
PythonJavaScriptGoRust
Integer overflownever (grows)precision lost above 2^53wraps silentlypanic in debug, wraps in release, or you choose
Mixing int and floatautomaticeverything is a floatcompile errorcompile error, use as
MoneyDecimal or int centsint centsint centsint paisa (u64)

Key takeaway

Every number in Rust has a fixed-size type: u types for counts that can't go negative, i types for values that can, f64 for fractions, plus bool and char. Pick a type big enough for the largest value it will ever hold. Debug builds panic on overflow, release builds wrap, and checked_, saturating_ and wrapping_ let you choose on purpose. Rust never converts between number types for you; use as. Keep money in whole paisa.

Practice

Objective: do money maths safely with integers and checked_sub.

Challenge: a customer has ৳500.00 in their wallet and buys rice (৳420.00) and oil (৳185.50). Keep everything in paisa as u64. Print the bill in taka with two decimals, then use checked_sub to either pay and print what's left, or print how many paisa they are short.

Expected result:

bill: 605.50 taka
not enough balance, short by 10550 paisa
Hint 1

৳185.50 is 18_550 paisa. Taka is paisa / 100, and the paisa part is paisa % 100 (the remainder).

Hint 2

{:02} prints a number with at least two digits, so 5 paisa shows as 05.

Hint 3

wallet_paisa.checked_sub(bill) returns Option<u64>. match on it with Some(left) => ... and None => ....

Solution
fn main() {
    let wallet_paisa: u64 = 50_000; // ৳500.00
    let rice: u64 = 42_000; // ৳420.00
    let oil: u64 = 18_550; // ৳185.50
    let bill = rice + oil;
    println!("bill: {}.{:02} taka", bill / 100, bill % 100);

    match wallet_paisa.checked_sub(bill) {
        Some(left) => println!("paid, {}.{:02} taka left", left / 100, left % 100),
        None => println!("not enough balance, short by {} paisa", bill - wallet_paisa),
    }
}

Try plain wallet_paisa - bill instead of checked_sub. Here every number is written in the code, so the compiler works it out and refuses to build: error: this arithmetic operation will overflow. In a real shop the numbers come from the database at runtime, and then a debug build panics with attempt to subtract with overflow, while a release build wraps around to 18446744073709541066 paisa of change. checked_sub makes you decide what "not enough money" means.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →