5 / 35

Rust Basics· 13 min read· Lesson 5 of 35

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:

Output
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 type

Here 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:

  • i or u: 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.

src/main.rs
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");
}
Output
Total: 775 cents
Total: $7.75
Fridge temperature changed by -3 degrees
  1. Both prices are u32, so total is a u32 too (Rust infers it).
  2. total / 100 is integer division: it throws away any remainder. 775 / 100 gives 7, the dollars.
  3. total % 100 is the remainder operator: 775 % 100 gives 75, the cents.
  4. {:02} is a placeholder that pads a number to 2 digits with zeros, so 5 cents prints as 05, not 5.
  5. temperature_change can be negative, so it uses the signed type i32.

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:

Output
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 negated

Each 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.

src/main.rs
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);
}
Output
Rating: 4.7
3 vs 3.5
0.30000000000000004
  1. average_rating is a good use of a float: the average of customer reviews.
  2. 7 / 2 uses integers, so the remainder is dropped and you get 3. 7.0 / 2.0 uses floats and gives 3.5.
  3. Look at the last line! 0.1 + 0.2 isn’t exactly 0.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.

src/main.rs
fn main() {
let is_open = true;
let has_oat_milk: bool = false;
println!("Open? {is_open}. Oat milk? {has_oat_milk}");
}
Output
Open? true. Oat milk? false

Booleans 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.
src/main.rs
fn main() {
let cafe_name: &str = "Rusty Bean Café";
let mut customer = String::from("Ada");
customer.push_str(" Lovelace");
println!("{cafe_name} welcomes {customer}!");
}
Output
Rusty Bean Café welcomes Ada Lovelace!
  1. cafe_name is a &str, fixed text from our code.
  2. String::from("Ada") creates a growable String starting with “Ada”.
  3. push_str adds more text onto the end. That only works because customer is a String and is mut.

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.

src/main.rs
fn main() {
let latte: (&str, u32) = ("Latte", 450);
println!("{} costs {} cents", latte.0, latte.1);
let (name, price) = latte;
println!("{name}: {price}");
}
Output
Latte costs 450 cents
Latte: 450
  1. The type (&str, u32) says “a tuple with some text, then a u32”. Values go in round brackets.
  2. latte.0 gets the first item and latte.1 the second. Counting starts at 0.
  3. 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.

src/main.rs
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);
}
Output
First price: 300
Number of items: 3
All prices: [300, 450, 325]
[0, 0, 0, 0, 0]
  1. [u32; 3] means “an array of three u32 values”. Items go in square brackets.
  2. prices[0] gets the first item. Positions (called indexes) start at 0, so the last one here is prices[2].
  3. .len() gives the number of items.
  4. {:?} is the debug placeholder. It prints things like arrays that {} can’t.
  5. [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:

  1. Make a tuple espresso holding the name "Espresso" and the price 300 (as u32).
  2. Make an array order of three u32 prices: 300, 450 and 325.
  3. Add up the three prices by index into a total variable.
  4. Print the espresso’s name and price, then print the total in dollars and cents, like $10.75.
Show solution
src/main.rs
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:

Output
Espresso costs 300 cents
Order total: $10.75

The 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…). u types can’t be negative. Floats (f64) have decimals but aren’t always exact, so store money as integer cents.
  • bool is true/false, and char is one character in single quotes.
  • &str is fixed text. String is 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

Search lessons

Type to search all lessons.