Rust Data Types

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…

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

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

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

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

⚠️ Types that make a sum get refused or come out wrong

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.

What you will learn