Data Types
Part 1 · Rust. Learn Rust's basic data types (integers, floats, booleans, characters, text, tuples and arrays) by modelling the Rusty Bean Café menu.
Every value in Rust has a type: a label saying what kind of value it is and what you can do with it. A latte’s price is a whole number. “Is the café open?” is yes or no. The café’s name is text. In this lesson you’ll meet Rust’s basic types and see why storing prices as whole cents is a smart move.
What is a type, and why care?
Think of the café’s storage room. Milk goes in the fridge, beans in airtight jars, cups on a shelf. Each kind of thing has the right container, and you can’t pour milk into the cup shelf.
Types work the same way. The type tells Rust how much memory a value needs and which operations make sense. You can add two prices, but adding a price to “Rusty Bean Café” makes no sense, and Rust will stop you before the program runs.
Type inference and annotations
You’ve already used types without writing them:
let latte_price = 450;Rust figured out that 450 is a number. This is called type inference: the compiler works out the type from the value and how you use it.
You can also state the type yourself with a type annotation, written as a colon and the type after the name:
let latte_price: u32 = 450;Read this as “latte_price is a u32 holding 450”. You must write annotations for constants, and you’ll want them whenever Rust can’t guess or when you want a specific type. When Rust can’t work a type out, it tells you:
error[E0284]: type annotations needed --> src/main.rs:2:9 |2 | let x = "5".parse().unwrap(); | ^ ----- type must be known at this point ...help: consider giving `x` an explicit typeHere parse could produce many kinds of number, so Rust asks you to choose, for example let x: u32 = ....
Tip
In VS Code, rust-analyzer shows inferred types in faint grey text next to your variables. It’s a great way to learn which type Rust picked.
Integers: whole numbers
An integer is a whole number with no decimal point: 0, 7, 450, -3. Rust has several integer types. The name tells you two things:
ioru:i(signed) can be negative.u(unsigned) can only be zero or positive.- The number: how many bits (tiny on/off switches) it uses. More bits means a bigger range.
| Type | Range | Café example |
|---|---|---|
u8 |
0 to 255 | cups in one order |
i32 |
about -2.1 billion to 2.1 billion | temperature change |
u32 |
0 to about 4.2 billion | price in cents |
i64 / u64 |
very, very large | total sales over many years |
usize |
depends on your computer | positions and lengths of lists |
If you don’t say otherwise, Rust uses i32 for whole numbers.
fn main() { let latte_price: u32 = 450; let croissant_price: u32 = 325; let total = latte_price + croissant_price; println!("Total: {total} cents"); println!("Total: ${}.{:02}", total / 100, total % 100);
let temperature_change: i32 = -3; println!("Fridge temperature changed by {temperature_change} degrees");}Total: 775 centsTotal: $7.75Fridge temperature changed by -3 degrees- Both prices are
u32, sototalis au32too (Rust infers it). total / 100is integer division: it throws away any remainder. 775 / 100 gives7, the dollars.total % 100is the remainder operator: 775 % 100 gives75, the cents.{:02}is a placeholder that pads a number to 2 digits with zeros, so 5 cents prints as05, not5.temperature_changecan be negative, so it uses the signed typei32.
You can write big numbers with underscores for readability: 1_000_000 is the same as 1000000.
Warning
An unsigned type can’t hold a negative number. Writing let refund: u32 = -50; fails with:
error[E0600]: cannot apply unary operator `-` to type `u32` --> src/main.rs:2:23 |2 | let refund: u32 = -50; | ^^^ cannot apply unary operator `-` | = note: unsigned values cannot be negatedEach type also has a maximum. A u8 can’t go past 255. If a calculation goes too high, that’s called overflow. Rust catches it when it can, and while developing, it stops the program rather than giving a wrong answer.
Floats: numbers with a decimal point
A floating-point number (or float) has a decimal point: 4.7, 3.5, 0.25. Rust has f32 and f64. Use f64 (the default). It’s more precise and just as fast on modern computers.
fn main() { let average_rating: f64 = 4.7; let whole_division = 7 / 2; let float_division = 7.0 / 2.0; println!("Rating: {average_rating}"); println!("{whole_division} vs {float_division}"); println!("{}", 0.1 + 0.2);}Rating: 4.73 vs 3.50.30000000000000004average_ratingis a good use of a float: the average of customer reviews.7 / 2uses integers, so the remainder is dropped and you get3.7.0 / 2.0uses floats and gives3.5.- Look at the last line!
0.1 + 0.2isn’t exactly0.3. Computers store floats in binary, and many decimal numbers can’t be stored exactly. It’s like trying to write 1/3 as a decimal: 0.3333… never quite ends.
Important
This is why Rusty Bean Café stores money as whole cents in a u32. Integers are always exact, so 450 + 325 is exactly 775. If prices were floats, tiny errors could pile up across thousands of orders, and the till would be off. Convert to dollars only when you display the price.
Booleans: true or false
A boolean (type bool) has only two possible values: true or false. It’s a light switch: on or off.
fn main() { let is_open = true; let has_oat_milk: bool = false; println!("Open? {is_open}. Oat milk? {has_oat_milk}");}Open? true. Oat milk? falseBooleans become really useful for decisions, like “if the café is open, take the order”. That’s the Control Flow lesson.
Characters: one letter or symbol
A char is a single character: a letter, digit, symbol, or even an emoji. Chars use single quotes.
let cup_size: char = 'L';let bean = '☕';'L' (single quotes) is one char. "L" (double quotes) is text, which is a different type. Mixing these up is a common early mistake.
Text: &str and String
Text in Rust comes in two main flavours. We’ll keep this light for now and explore it properly in later lessons.
&str(say “string slice”): text written directly in your code, like"Rusty Bean Café". It’s fixed: you can read it, but not grow it. Think of the café name painted on the window.String: text that can grow and change while the program runs, like a customer’s name typed into the till. Think of a whiteboard you can add to.
fn main() { let cafe_name: &str = "Rusty Bean Café"; let mut customer = String::from("Ada"); customer.push_str(" Lovelace"); println!("{cafe_name} welcomes {customer}!");}Rusty Bean Café welcomes Ada Lovelace!cafe_nameis a&str, fixed text from our code.String::from("Ada")creates a growableStringstarting with “Ada”.push_stradds more text onto the end. That only works becausecustomeris aStringand ismut.
Why two types? It’s about who owns the text and where it lives in memory, which is the topic of Ownership. For now: use &str for fixed text and String when it needs to change.
Tuples: a few values bundled together
A tuple groups a fixed number of values, which can be different types, into one value. It’s like a paper bag holding one drink and its price tag.
fn main() { let latte: (&str, u32) = ("Latte", 450); println!("{} costs {} cents", latte.0, latte.1);
let (name, price) = latte; println!("{name}: {price}");}Latte costs 450 centsLatte: 450- The type
(&str, u32)says “a tuple with some text, then au32”. Values go in round brackets. latte.0gets the first item andlatte.1the second. Counting starts at 0.let (name, price) = latte;unpacks the tuple into two variables at once. This is called destructuring.
Arrays: a fixed-size list of the same type
An array holds several values of the same type, and its length can never change. Think of an egg carton: exactly 12 slots, all for eggs.
fn main() { let prices: [u32; 3] = [300, 450, 325]; println!("First price: {}", prices[0]); println!("Number of items: {}", prices.len()); println!("All prices: {:?}", prices);
let empty_cups = [0; 5]; println!("{:?}", empty_cups);}First price: 300Number of items: 3All prices: [300, 450, 325][0, 0, 0, 0, 0][u32; 3]means “an array of threeu32values”. Items go in square brackets.prices[0]gets the first item. Positions (called indexes) start at 0, so the last one here isprices[2]..len()gives the number of items.{:?}is the debug placeholder. It prints things like arrays that{}can’t.[0; 5]is a shortcut for “five zeros”.
Asking for prices[3] would be reaching for a fourth egg in a three-egg carton. Rust won’t let your program read memory it doesn’t own: if it can spot the mistake while compiling, it refuses with index out of bounds: the length is 3 but the index is 3. Otherwise the program stops with that message when it runs.
When you need a list that can grow (like today’s orders), you’ll use a Vec instead. That’s coming in Collections.
Try it yourself
Model one menu item and a small order:
- Make a tuple
espressoholding the name"Espresso"and the price300(asu32). - Make an array
orderof threeu32prices:300,450and325. - Add up the three prices by index into a
totalvariable. - Print the espresso’s name and price, then print the total in dollars and cents, like
$10.75.
Show solution
fn main() { let espresso: (&str, u32) = ("Espresso", 300); let order: [u32; 3] = [300, 450, 325];
let total = order[0] + order[1] + order[2];
println!("{} costs {} cents", espresso.0, espresso.1); println!("Order total: ${}.{:02}", total / 100, total % 100);}Output:
Espresso costs 300 centsOrder total: $10.75The total stays exact because it’s whole cents in a u32. Only the display splits it into dollars (/ 100) and cents (% 100).
Recap
- Every value has a type. Rust usually infers it, and you can write it with an annotation like
: u32. - Integers are whole numbers (
i32,u32,u8…).utypes can’t be negative. Floats (f64) have decimals but aren’t always exact, so store money as integer cents. boolistrue/false, andcharis one character in single quotes.&stris fixed text.Stringis text that can grow.- Tuples bundle a few values of different types. Arrays hold a fixed number of values of one type, indexed from 0.
What’s next
You can store all kinds of café data now. Next, learn to package up reusable steps like “calculate the total” in Functions.
0 of 35 lessons complete