Blog

Part 2 · Variables and Types in Rust: let, mut, Shadowing and Overflow

Rust variables can’t change unless you say mut, every value has a fixed type, and an integer that overflows stops a debug build. This part covers let, mut, shadowing, const, the number types, char, as casts and overflow.

In Rust, a variable can’t change unless you ask for it. Every value has a type with a fixed size, and the compiler checks that the types fit together before the program runs. Most surprises in your first week of Rust come from one of those two facts.

This part covers let and mut, shadowing, const, type inference, the number types, bool and char, casts with as, and what happens when a number gets too big for its type. It builds on Part 1, where we made a project with cargo new and read our first compiler error. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

Read this program and decide what it prints before you scroll down:

fn main() {
    let count = 1;
    println!("count is {count}");
    count = count + 1;
    println!("count is {count}");
}

It prints nothing. It doesn’t compile:

error[E0384]: cannot assign twice to immutable variable `count`
 --> src/main.rs:4:5
  |
2 |     let count = 1;
  |         ----- first assignment to `count`
3 |     println!("count is {count}");
4 |     count = count + 1;
  |     ^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     let mut count = 1;
  |         +++

In most languages this prints 1 and then 2. In Rust, let count = 1 makes a variable that can’t change. The compiler calls it immutable. Line 4 tries to change it, so the build stops.

The error points at line 4, which broke the rule, and at line 2, where count got its value. The help: part shows the fix, and the +++ marks what to add: the word mut.

let and mut

let makes a new variable. Add mut (short for mutable) when you plan to change it. With let mut count = 1;, the program above compiles and prints count is 1 and then count is 2. You can also write count += 1, which is short for count = count + 1. Rust has +=, -=, *=, /= and %=, but no ++.

Why is “can’t change” the default? Most variables never change after they get their value. So mut works as a flag for the reader: watch this one, something changes it later. A variable without mut keeps its value, and the compiler holds you to that. If you write mut and never change the variable, the compiler warns: “variable does not need to be mutable”.

Shadowing: a new variable with the same name

You can write let again with a name you’ve already used. That makes a second, new variable, and it hides the first one. This is called shadowing:

fn main() {
    let spaces = "   ";
    let spaces = spaces.len();
    println!("{spaces} spaces");

    let x = 5;
    {
        let x = x * 2;
        println!("inside the block, x = {x}");
    }
    println!("after the block, x = {x}");
}

It prints:

3 spaces
inside the block, x = 10
after the block, x = 5

The first spaces is text. The second spaces is a number, its length. They’re two variables that share a name, so they can have different types.

The curly braces make a scope, a region where names live. The inner x exists only inside the braces. When the block ends, it goes away and the outer x is visible again, still 5. Shadowing hid the outer x for a while. It never changed it.

Try the first half with mut instead, and it fails:

fn main() {
    let mut spaces = "   ";
    spaces = spaces.len();
    println!("{spaces}");
}

It prints:

error[E0308]: mismatched types
 --> src/main.rs:3:14
  |
2 |     let mut spaces = "   ";
  |                      ----- expected due to this value
3 |     spaces = spaces.len();
  |              ^^^^^^^^^^^^ expected `&str`, found `usize`

mut lets a variable change its value, never its type. spaces started as a &str, the type of text in quotes (Part 5 covers strings), so a number can’t go into it. The rule of thumb:

  • use mut for one thing changing over time, like a counter or a running total;
  • use shadowing when you turn a value into a new form and won’t need the old one, like text into a number.

Constants

A const is a value fixed for the whole program:

const SECONDS_PER_HOUR: u32 = 60 * 60;
const MAX_PLAYERS: usize = 8;

fn main() {
    let hours = 3;
    println!("{} seconds", hours * SECONDS_PER_HOUR);
    println!("up to {MAX_PLAYERS} players");
}

It prints:

10800 seconds
up to 8 players

A const can sit outside any function, so every function in the file can use it. It must have a type: const LIMIT = 10; is an error, “missing type for const item”. Its value must be known when the program compiles, so 60 * 60 is fine, but a value typed in by the user isn’t. It can never be mut, and its name is in capitals by convention.

Type inference, and when you must say the type

Every value has one type, fixed when the program compiles. You rarely write it, because the compiler works it out. This is type inference. std::any::type_name_of_val lets us ask what it worked out:

use std::any::type_name_of_val;

fn main() {
    let a = 42;
    let b = 3.5;
    let e = 42u8;
    let f: i64 = 42;
    println!("a: {}", type_name_of_val(&a));
    println!("b: {}", type_name_of_val(&b));
    println!("e: {}", type_name_of_val(&e));
    println!("f: {}", type_name_of_val(&f));
}

It prints:

a: i32
b: f64
e: u8
f: i64

A whole number with nothing else to go on is an i32. A number with a decimal point is an f64. To pick another type, put a suffix on the number, as in 42u8, or write the type after the name, as in let f: i64 = 42. That second form is a type annotation. (The & in &a lends a to the function. Part 7 explains it; for now, read it as “look at a“.)

Sometimes the compiler can’t decide. Turning text into a number is the usual case, because parse can make many number types:

fn main() {
    let guess = "42".parse().unwrap();
    println!("{guess}");
}

It prints:

error[E0284]: type annotations needed
 --> src/main.rs:2:9
  |
2 |     let guess = "42".parse().unwrap();
  |         ^^^^^        ----- type must be known at this point
...
help: consider giving `guess` an explicit type

Should “42” become an i32, a u8 or an f64? Nothing says, so the compiler asks. You can answer in two ways:

fn main() {
    let input = " 42 ";
    let input: u32 = input.trim().parse().unwrap();
    println!("{}", input * 2);

    let small = "42".parse::<u8>().unwrap();
    println!("{small}");
}

It prints:

84
42

The first is an annotation on the variable. It’s also shadowing used the way it’s meant to be: the text input becomes the number input. The second puts the type on parse itself with ::<u8>, a shape Rust programmers call the turbofish. unwrap means “give me the number, or stop the program if the text isn’t one”. Part 12 handles that failure properly.

The integer types

Rust has five pairs of integer types with fixed sizes, and one pair whose size depends on the machine. i means signed (it can be negative), u means unsigned (zero or more), and the number is the size in bits: i8, i16, i32, i64, i128, the same with u, and isize and usize. Each type has MIN and MAX constants:

fn main() {
    println!("u8    {} to {}", u8::MIN, u8::MAX);
    println!("i8    {} to {}", i8::MIN, i8::MAX);
    println!("i32   {} to {}", i32::MIN, i32::MAX);
    println!("u64   {} to {}", u64::MIN, u64::MAX);
    println!("usize {} to {}", usize::MIN, usize::MAX);
}

It prints:

u8    0 to 255
i8    -128 to 127
i32   -2147483648 to 2147483647
u64   0 to 18446744073709551615
usize 0 to 18446744073709551615

8 bits have 2⁸ = 256 possible patterns. u8 uses them for 0 to 255. i8 gives half of them to negative numbers, so it runs from -128 to 127. Every pair follows the same pattern. The figure shows all five pairs:

each box is 1 byte (8 bits) u = unsigned, i = signed u8 / i8 8 bits u8 0 to 255 i8 -128 to 127 u16 / i16 16 bits u16 0 to 65,535 i16 -32,768 to 32,767 u32 / i32 32 bits i32 is the default u32 0 to 4,294,967,295 i32 -2,147,483,648 to 2,147,483,647 u64 / i64 64 bits u64 0 to about 1.8 × 10¹⁹ i64 about ±9.2 × 10¹⁸ u128 / i128 128 bits u128 0 to about 3.4 × 10³⁸ i128 about ±1.7 × 10³⁸ usize / isize: 8 bytes on a 64-bit machine, the same range as u64 / i64

Each step up doubles the bytes. The unsigned type starts at zero, and the signed type of the same size splits its range around zero.

usize and isize are as big as a memory address: 8 bytes on a 64-bit machine, which is why usize printed the same range as u64. Rust uses usize for sizes and positions. .len() returns one, and you index a list with one.

Which should you pick? i32 unless you have a reason. usize for lengths and indexes. u8 for raw bytes. i64 or u64 when values can pass two billion, like file sizes or times in milliseconds.

You can write 1_000_000 for a million (Rust ignores the underscores), 0xff for hex, 0b1010 for binary, and b'A' for the byte value of a letter, which is a u8.

Floats, bool and char

Rust has two floating-point types: f64, the default, and f32, which is half the size and keeps fewer digits. They follow the same standard (IEEE 754) as floats in most languages, so they round the same way:

fn main() {
    println!("{}", 0.1 + 0.2);
    println!("{}", 7.0 / 2.0);
    println!("{}", 7 / 2);
    println!("{}", -7 / 2);
    println!("{}", 7 % 2);
}

It prints:

0.30000000000000004
3.5
3
-3
1

7 / 2 divides two integers, so the answer is an integer, 3. Rust drops the fraction toward zero, so -7 / 2 is -3, not -4. % is the remainder.

Rust never mixes integers and floats for you:

fn main() {
    let items = 3;
    let price = 2.5;
    let total = items * price;
    println!("{total}");
}

It prints:

error[E0277]: cannot multiply `{integer}` by `{float}`
 --> src/main.rs:4:23
  |
4 |     let total = items * price;
  |                       ^ no implementation for `{integer} * {float}`

{integer} means “some integer type, not decided yet”. Make both sides the same type: write let items = 3.0;, or convert with as, which comes next.

A bool is true or false and takes 1 byte. A char is one Unicode character in single quotes. (Double quotes make a string, a different type.) A char always takes 4 bytes, because it holds the character’s Unicode number:

fn main() {
    let a = 'A';
    let e = 'é';
    let crab = '🦀';
    println!("{a} {e} {crab}");
    println!("{} {} {}", a as u32, e as u32, crab as u32);
    println!("char takes {} bytes", std::mem::size_of::<char>());
    println!("{} {}", a.is_alphabetic(), '7'.is_ascii_digit());
}

It prints:

A é 🦀
65 233 129408
char takes 4 bytes
true true

The crab is number 129,408, too big for 2 bytes. The precise name for what a char holds is a Unicode scalar value: any Unicode number except a small reserved range. Part 5 shows why a String doesn’t store its text as 4-byte chars.

Casting with as

as converts between number types. It never fails and never stops the program. That sounds helpful until you see what it does with a value that doesn’t fit:

fn main() {
    let big: i32 = 300;
    let negative: i32 = -1;
    let price: f64 = 3.99;
    println!("300 as u8    = {}", big as u8);
    println!("-1 as u32    = {}", negative as u32);
    println!("3.99 as i32  = {}", price as i32);
    println!("-3.99 as i32 = {}", -price as i32);
    println!("1e10 as i32  = {}", 1e10_f64 as i32);
    println!("-1.5 as u8   = {}", -1.5_f64 as u8);
    let nan = f64::NAN;
    println!("NaN as i32   = {}", nan as i32);
    println!("97 as char   = {}", 97u8 as char);
}

It prints:

300 as u8    = 44
-1 as u32    = 4294967295
3.99 as i32  = 3
-3.99 as i32 = -3
1e10 as i32  = 2147483647
-1.5 as u8   = 0
NaN as i32   = 0
97 as char   = a

Each line follows a rule:

  • To a smaller integer, it keeps the low bits. 300 is 1_0010_1100 in binary, 9 bits. A u8 keeps the last 8, 0010_1100, which is 44. Nothing warns you.
  • Signed to unsigned reuses the bits. -1 in an i32 is 32 one-bits. Read as a u32, they’re 4,294,967,295.
  • Float to integer drops the fraction toward zero, and clamps at the edges: too big becomes MAX, too small becomes MIN, and NaN (not a number) becomes 0.
  • Only a u8 can become a char with as. 65u32 as char is error E0604. Use char::from_u32.

When a conversion can’t lose anything, use From instead: u32::from(x) turns a u8 into a u32. From only exists for the safe directions, so u8::from on an i32 doesn’t compile. When a value might not fit, u8::try_from checks it first. The first worked example below uses both.

Overflow

What happens when a number gets too big for its type? First, the case the compiler can see:

fn main() {
    let level: u8 = 255;
    let next = level + 1;
    println!("{next}");
}

It prints:

error: this arithmetic operation will overflow
 --> src/main.rs:3:16
  |
3 |     let next = level + 1;
  |                ^^^^^^^^^ attempt to compute `u8::MAX + 1_u8`, which would overflow

Overflow means the answer doesn’t fit in the type. The compiler worked out 255 + 1 while compiling, saw that 256 doesn’t fit in a u8, and refused. This error has no code, because it comes from a lint, an extra check that’s set to stop the build. let level: u8 = 256; is refused the same way, by a lint that says “literal out of range for u8“.

Usually, though, the compiler can’t know the value, because it changes as the program runs:

fn main() {
    let mut level: u8 = 253;
    for _ in 0..5 {
        level += 1;
        println!("level {level}");
    }
}

It prints:

level 254
level 255
...
panicked at src/main.rs:4:9:
attempt to add with overflow

for _ in 0..5 runs its body five times (Part 3 covers loops). At 255, adding 1 made the program panic: stop on purpose, with a message. The full line starts with thread 'main' and a thread number that changes from run to run. Then comes src/main.rs:4:9, the file, line and column of the +=, and the reason.

That’s a debug build, the kind cargo run makes. A release build, from cargo run --release, is faster and leaves the check out. We ran the same program that way, and it printed:

level 254
level 255
level 0
level 1
level 2

No error. 255 + 1 wrapped around to 0, like a car’s odometer rolling over from 999999 to 000000. That’s a wrong answer, delivered quietly. You can keep the check in release builds by adding overflow-checks = true under [profile.release] in Cargo.toml.

To see the panic in a tiny test program, hide the value from the compiler with std::hint::black_box. It returns its argument unchanged, but the compiler treats the result as unknown:

use std::hint::black_box;

fn main() {
    let level: u8 = black_box(255);
    let next = level + 1;
    println!("{next}");
}

It prints:

panicked at src/main.rs:5:16:
attempt to add with overflow

Choosing what overflow means

A debug panic tells you about an overflow, but not what you wanted instead. Four families of methods say it in the code, and they behave the same in debug and release builds:

fn main() {
    let a: u8 = 250;
    let b: u8 = 10;
    println!("wrapping_add:    {}", a.wrapping_add(b));
    println!("checked_add:     {:?}", a.checked_add(b));
    println!("checked_add 5:   {:?}", a.checked_add(5));
    println!("saturating_add:  {}", a.saturating_add(b));
    println!("overflowing_add: {:?}", a.overflowing_add(b));
    println!("saturating_sub:  {}", b.saturating_sub(a));
}

It prints:

wrapping_add:    4
checked_add:     None
checked_add 5:   Some(255)
saturating_add:  255
overflowing_add: (4, true)
saturating_sub:  0

250 + 10 is 260, which doesn’t fit in a u8:

  • wrapping_add wraps around: 260 – 256 = 4. Use it when wrapping is the point, as in hashes and checksums.
  • checked_add gives None on overflow and Some(answer) otherwise. Part 11 covers Option; for now, None means “there is no answer”. Use it when overflow means bad input.
  • saturating_add stops at the edge, 255, and saturating_sub stops at 0. Use it for things like volume, where “as far as it goes” is right.
  • overflowing_add gives the wrapped answer and a bool that says whether it wrapped.

Each family also has _sub, _mul, _div and more. The {:?} in println! is the debug format, which prints values like None and (4, true).

Worked example: averaging three readings

A sensor gives readings from 0 to 255, so u8 looks right:

fn average(a: u8, b: u8, c: u8) -> u8 {
    (a + b + c) / 3
}

fn main() {
    println!("{}", average(10, 20, 30));
    println!("{}", average(200, 100, 50));
}

It prints:

20
...
panicked at src/main.rs:2:6:
attempt to add with overflow

fn average(...) -> u8 is a function that returns a u8; Part 3 covers functions. The first call works and the second panics. Read the location: line 2, column 6 is where a + b starts. That’s the clue. Each reading fits in a u8, and so does the average, 116. But the sum on the way there is 350. Adding two u8 values gives a u8, so the sum overflows. The compiler didn’t catch it, because average doesn’t know its arguments until it’s called.

The fix is to add in a bigger type. Three readings add up to at most 765, and a u16 holds up to 65,535:

fn average(a: u8, b: u8, c: u8) -> u8 {
    let sum = u16::from(a) + u16::from(b) + u16::from(c);
    let avg = sum / 3;
    u8::try_from(avg).unwrap()
}

fn main() {
    println!("{}", average(10, 20, 30));
    println!("{}", average(200, 100, 50));
    println!("{}", average(255, 255, 255));
}

It prints:

20
116
255

u16::from widens each reading, which can’t lose anything. u8::try_from goes back down and checks that the value fits. It returns a Result (Part 12), and unwrap stops the program if it doesn’t fit. The average of three u8 values always fits, so that never happens here. We still use try_from rather than as u8. If someone changes the formula later and breaks that promise, the program stops with a message instead of returning a wrong number.

Worked example: padding names in a column

We want each name followed by dots, so the names fill a 10-character column. .len() gives a name’s length, and ".".repeat(n) makes n dots:

fn main() {
    let width = 10;
    for name in ["Ana", "Benedict", "Maximiliano"] {
        let dots = width - name.len();
        println!("{name}{}|", ".".repeat(dots));
    }
}

It prints:

Ana.......|
Benedict..|
...
panicked at src/main.rs:4:20:
attempt to subtract with overflow

The square brackets make an array (Part 4); here it’s three names to loop over. “Maximiliano” has 11 letters, so width - name.len() is 10 – 11. width is a usize, inferred from name.len(), and a usize can’t go below zero. Going below zero is overflow too, and this time the panic says “subtract”.

A long name should get no dots, so saturating_sub looks like the fix:

fn main() {
    let width = 10;
    for name in ["Ana", "Benedict", "Maximiliano"] {
        let dots = width.saturating_sub(name.len());
        println!("{name}{}|", ".".repeat(dots));
    }
}

It prints:

error[E0689]: can't call method `saturating_sub` on ambiguous numeric type `{integer}`
 --> src/main.rs:4:26
...
help: you must specify a type for this binding, like `i32`
  |
2 |     let width: i32 = 10;

This one surprises people. With -, the compiler worked out the type of width from the other side. To call a method on width, it needs the type first, because every integer type has its own saturating_sub. The help: says i32, but that’s only an example. name.len() is a usize, so width must be one too:

fn main() {
    let width: usize = 10;
    for name in ["Ana", "Benedict", "Maximiliano"] {
        let dots = width.saturating_sub(name.len());
        println!("{name}{}|", ".".repeat(dots));
    }
}

It prints:

Ana.......|
Benedict..|
Maximiliano|

One caution: .len() counts bytes, not letters. For these names that’s the same. Part 5 shows a name where it isn’t.

Tips and traps

  • Forgetting mut. Error E0384, “cannot assign twice to immutable variable”. Add mut, as the help: line shows. If you didn’t mean to change the variable, the bug is the assignment, not the missing mut.
  • Using mut to change a type. E0308, “mismatched types”. A variable keeps its type for life. Shadow it with a new let instead.
  • Trusting as to check. 300 as u8 is 44, with no warning. Use From where nothing can be lost and try_from where it can. Keep as for when you want the bits as they are.
  • Subtracting lengths. a.len() - b.len() panics when b is longer. Use saturating_sub if 0 is the right answer, checked_sub if it means a mistake, or abs_diff for the distance either way.
  • Testing only in debug. Overflow panics in debug and wraps quietly in release. Where it matters, write checked_, wrapping_ or saturating_ so the code means the same in both.
  • Calling a method on a bare number. E0689, “ambiguous numeric type”. Annotate the variable, or add a suffix, as in 10usize.
  • Adding small types. Two u8 values add up to a u8, so the sum can overflow even when the final answer fits. Widen first with u16::from or u32::from.

A value’s type decides how big it can get, and Rust won’t quietly change either.

Exercises

Exercise 1. Without running it, decide what this prints:

let x = 1;
let x = x + 1;
{
    let x = x * 10;
    println!("{x}");
}
let mut y = x;
y += 1;
println!("{x} {y}");

Exercise 2. This program should print 20! (1 × 2 × 3 × … × 20), but it panics. Change one type so it works.

fn main() {
    let mut f: i32 = 1;
    for n in 1..=20 {
        f *= n;
    }
    println!("20! = {f}");
}

It prints:

attempt to multiply with overflow

Exercise 3. Write a program that finds the largest factorial that fits in a u64, without writing 20 anywhere. Use overflowing_mul, so it never panics. It should print:

20! = 2432902008176640000 is the last one that fits in u64
Answers

1. The second let x shadows the first, so x is 2. Inside the block, a third x is 20, and the first println! shows it. After the block, x is 2 again. y starts as a copy of x and becomes 3, which doesn’t touch x.

fn main() {
    let x = 1;
    let x = x + 1;
    {
        let x = x * 10;
        println!("{x}");
    }
    let mut y = x;
    y += 1;
    println!("{x} {y}");
}

It prints:

20
2 3

2. 13! is 6,227,020,800, more than an i32 can hold. A u64 goes up to about 1.8 × 10¹⁹, and 20! is about 2.4 × 10¹⁸. Change i32 to u64. n becomes a u64 too, inferred from f *= n.

fn main() {
    let mut f: u64 = 1;
    for n in 1..=20 {
        f *= n;
    }
    println!("20! = {f}");
}

It prints:

20! = 2432902008176640000

3. overflowing_mul returns the result and a bool. When the bool is true, the previous factorial was the last that fits. break leaves the loop early (Part 3), and let (next, overflowed) = ... takes the pair apart (Part 4).

fn main() {
    let mut f: u64 = 1;
    for n in 2..100 {
        let (next, overflowed) = f.overflowing_mul(n);
        if overflowed {
            println!("{}! = {f} is the last one that fits in u64", n - 1);
            break;
        }
        f = next;
    }
}

It prints:

20! = 2432902008176640000 is the last one that fits in u64

What’s next

So far, all our code has lived in main. In Part 3, we’ll write our own functions, use if and loop, and see why almost everything in Rust, an if included, gives back a value.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.