Rust for Pythonistas

Lesson 3 of 26

Hello, variables and mut

Python runs a file from top to bottom. Rust is compiled: before anything runs, the compiler reads the whole program, checks it, and only then builds something you can run. Most of what looks strange in Rust is there so the compiler can catch mistakes before the program runs.

Three things you will see in every Rust file:

  • fn main() { ... } is where the program starts.
  • Curly braces { } mark blocks. Python uses indentation for this. Rust code is indented too, but only so people can read it.
  • Most lines end with ;.

Hello and two variables

An almost line-by-line translation. Hover over the marked Rust lines.

Python
name = "Ferris"
age = 7
print(f"Hello, {name}! You are {age}.")
Rust
fn main() {
    let name = "Ferris";
    let age = 7;
    println!("Hello, {name}! You are {age}.");
}
Output
Hello, Ferris! You are 7.

Variables are read-only unless you say mut

In Python any name can be reassigned. In Rust a variable cannot change unless it is declared with mut (short for mutable). When reading Rust, mut tells you which variables to watch: everything else stays the same once it is set.

Python
count = 0
count += 1
count += 1
print(count)
Rust
fn main() {
    let mut count = 0;
    count += 1;
    count += 1;
    println!("{count}");
}
Output
2

Forgetting mut is a compile error

Python is fine with this. Rust refuses to build it, and the error message is clear. Learning to read these messages is a big part of reading Rust, and lesson 15 covers it.

Python
total = 10
total = total + 5
print(total)
Rust
fn main() {
    let total = 10;
    total = total + 5;
    println!("{total}");
}
Output
15

Shadowing: a new variable with the same name

A second let with the same name creates a new variable that hides the old one, and it may have a different type. You will often see this when converting a value, like text to a number. It is not mut: no variable changes here.

Python
text = "42"
text = int(text)
print(text + 1)
Rust
fn main() {
    let text = "42";
    let text: i32 = text.parse().unwrap();
    println!("{}", text + 1);
}
Output
43

Where the Python analogy breaks

Cheat card

PythonRust
print("hi")println!("hi");
print(f"{x} and {y}")println!("{x} and {y}");
print(f"{x + 1}")println!("{}", x + 1);
print(repr(items))println!("{:?}", items);
s = f"{x}!"let s = format!("{x}!");
x = 5let x = 5;
x = 5 x += 1let mut x = 5; x += 1;
n: int = 5let n: i32 = 5;
MAX = 100 # by conventionconst MAX: u32 = 100;
# comment// comment
"""docstring"""/// doc comment
if __name__ == "__main__":fn main() { }

← A tiny app: a function and a module Numbers and strings →