Rust for Pythonistas

Lesson 6 of 26

if, loops and ranges

Rust's if looks like Python's, with two differences: no parentheses around the condition, and the braces are always required. Rust also has no truthiness. The condition must be a real bool, so an empty string or the number 0 is not "false" to Rust. You compare instead: n != 0, !text.is_empty().

Loops are close to Python. for i in 0..5 is for i in range(5). The two dots make a range, and it stops before the last number. Write 0..=5 when you want the 5 included. while works as you expect. Rust also has loop, a loop with no condition, which you leave with break.

if, else if, else

Read the Rust side for three things: no parentheses, braces instead of indentation, and else if where Python writes elif.

Python
score = 72
if score >= 90:
    print("A")
elif score >= 70:
    print("B")
else:
    print("C")
Rust
fn main() {
    let score = 72;
    if score >= 90 {
        println!("A");
    } else if score >= 70 {
        println!("B");
    } else {
        println!("C");
    }
}
Output
B

There is no truthiness

Python asks "is this value falsy?" Rust has no such question, so this does not compile. To say the same thing in Rust, ask a question that has a yes or no answer: if !name.is_empty(). The ! is "not". For a number you write if n != 0, and for a list if !items.is_empty().

Python
name = ""
if name:
    print("has a name")
else:
    print("empty")
Rust
fn main() {
    let name = String::new();
    if name {
        println!("has a name");
    } else {
        println!("empty");
    }
}
Output
empty

for and ranges

One line per Python loop. 0..3 stops before 3, like range(3). 3..=5 includes 5, like range(3, 6). Ranges also have methods: step_by is the third argument of range, and rev counts down.

Python
for i in range(3):
    print(i)
for i in range(3, 6):
    print(i)
for i in range(0, 10, 2):
    print(i)
for i in range(4, 0, -1):
    print(i)
Rust
fn main() {
    for i in 0..3 {
        println!("{i}");
    }
    for i in 3..=5 {
        println!("{i}");
    }
    for i in (0..10).step_by(2) {
        println!("{i}");
    }
    for i in (1..=4).rev() {
        println!("{i}");
    }
}
Output
0
1
2
3
4
5
0
2
4
6
8
4
3
2
1

while and continue

This adds up the odd numbers below 10. continue jumps to the next round of the loop and skips the rest of the body, exactly like in Python.

Python
n = 0
total = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    total += n
print(total)
Rust
fn main() {
    let mut n = 0;
    let mut total = 0;
    while n < 10 {
        n += 1;
        if n % 2 == 0 {
            continue;
        }
        total += n;
    }
    println!("{total}");
}
Output
25

loop, and break with a value

loop is while True. The useful part is that break can hand a value out, and that value becomes the value of the whole loop. Here the loop is assigned to found, which is why there is a ; after its closing brace.

You will also meet labels: 'outer: for i in 0..3 { ... break 'outer; }. A label lets break leave both loops at once. Python has no direct equivalent.

Python
n = 6
steps = 0
while True:
    if n % 2 == 0:
        n = n // 2
    elif n == 1:
        break
    else:
        n = 3 * n + 1
    steps += 1
print(f"{n} after {steps} steps")
Rust
fn main() {
    let mut n = 6;
    let mut steps = 0;
    let found = loop {
        if n % 2 == 0 {
            n = n / 2;
        } else if n == 1 {
            break n;
        } else {
            n = 3 * n + 1;
        }
        steps += 1;
    };
    println!("{found} after {steps} steps");
}
Output
1 after 8 steps

Where the Python analogy breaks

Cheat card

PythonRust
if x > 0:if x > 0 {
elif x == 0:} else if x == 0 {
else:} else {
if items:if !items.is_empty() {
for i in range(5):for i in 0..5 {
for i in range(1, 6):for i in 1..=5 {
for i in range(0, 10, 2):for i in (0..10).step_by(2) {
for i in range(5, 0, -1):for i in (1..=5).rev() {
while n > 0:while n > 0 {
while True:loop {
breakbreak;
continuecontinue;

← Functions and expressions Vec and HashMap →