Rust for Pythonistas

Lesson 4 of 26

Numbers and strings

Python has one integer type, int, and one float type, float. Both grow as big as you need, and you rarely think about them. Rust has a menu of number types instead, each with a fixed size in bits, and the compiler has to know which one you mean before the program runs.

The good part: a fixed size means you can tell the range and the memory cost from the name alone. The types you will meet most:

  • i32, i64: whole numbers that can be negative. i32 is the default for a whole number with no annotation.
  • u8, u32, usize: whole numbers that cannot be negative. usize is the type of lengths and indexes.
  • f64: a float in 64 bits. Python's float is the same thing. Prefer f64 over f32 unless you have a reason.

Strings also come in two types, and telling them apart is the main skill here: &str is a borrowed view of text that already exists, and String is owned text you can grow.

A number type for every job

The same values as Python, each with a Rust type. The type goes after the name with a colon, like a Python type hint, except here it decides what the value is: an i64 holds numbers an i32 cannot.

Two small differences. bool values are true and false, always lowercase (Python writes True and False). A char is one character in single quotes: 'x'. Rust strings always use double quotes, so "x" is a string and 'x' is a char.

A fixed size also means a limit. An i32 stops at about 2.1 billion. In debug mode (the Playground's default, and cargo run's default) going past that limit panics, which is Rust's word for "crashes with an error". Python would just keep counting.

Python
count = 3
big = 9_000_000_000
ratio = 0.5
letter = "x"
print(count, big, ratio)
print(letter)
Rust
fn main() {
    let count: i32 = 3;
    let big: i64 = 9_000_000_000;
    let ratio: f64 = 0.5;
    let letter: char = 'x';
    println!("{count} {big} {ratio}");
    println!("{letter}");
}
Output
3 9000000000 0.5
x

Integer division, and the negative surprise

In Python / always gives a float, and // divides and rounds down. In Rust there is only /, and the types decide what it does: two floats give a float, two integers give an integer.

Here is the trap. Rust does not round down, it cuts off the decimal part:

  • 7 / 2 is 3 in both languages.
  • -7 / 2 is -3 in Rust, but -7 // 2 is -4 in Python.

For positive numbers you will not notice. For negative ones Rust moves toward zero and Python moves down. So Rust's / is Python's // only while the signs match. If you need Python's floor division, look for a helper in the code; plain / does not do it.

Python
print(7 / 2)
print(7 // 2)
Rust
fn main() {
    println!("{}", 7.0 / 2.0);
    println!("{}", 7 / 2);
}
Output
3.5
3

as: changing a number type

Rust never converts between number types by itself. Even 7 / 2.0 is a compile error when 7 is an i32. You convert with as, which you can read as "treat this value as the type that follows".

as is not always like float() or int(). When a float becomes an integer, as cuts off the decimal part and never rounds: 19.9 as i32 is 19. And a cast that does not fit, like 300 as u8, wraps around instead of raising an error. Use as when you know the value fits.

Python
a = 7
b = 2
ratio = a / b
total = 19.0
rounded = int(total)
print(ratio)
print(rounded)
Rust
fn main() {
    let a: i32 = 7;
    let b: i32 = 2;
    let ratio = a as f64 / b as f64;
    let total: f64 = 19.0;
    let rounded = total as i32;
    println!("{ratio}");
    println!("{rounded}");
}
Output
3.5
19

&str is borrowed, String is owned

A literal like "Ferris" has type &str: a borrowed view of text that is already stored inside the program. For now, read & as "borrowed: look at it, don't take it". Lesson 13 explains what the compiler does with that.

You cannot grow a &str. When you need to build or change text, use String: owned text that can grow. String::from("hi"), "hi".to_string() and format!("Hi {name}") all make one. push_str adds text and push adds a single char.

In function signatures, &str means "I only read this", and String means "I may keep or change it". &str is the type you see most in parameters.

Python
name = "Ferris"
message = f"Hello, {name}!"
message += " Welcome."
print(message)
print(len(message))
Rust
fn main() {
    let name: &str = "Ferris";
    let mut message = format!("Hello, {name}!");
    message.push_str(" Welcome.");
    println!("{message}");
    println!("{}", message.len());
}
Output
Hello, Ferris! Welcome.
23

len is bytes, chars are characters

This is a real gotcha. .len() on a string counts bytes, not characters. Python's len() counts characters, so the two disagree as soon as the text is not plain ASCII. The letter é takes two bytes in UTF-8, so "héllo".len() is 6 in Rust and 5 in Python.

To count characters in Rust, ask for the characters and count them: .chars().count(). That is the Python len(). Other string methods have direct Python matches: .to_uppercase() is .upper(), .trim() is .strip(), .contains(x) is x in s, and .split(x) is s.split(x) but gives an iterator, which lesson 8 covers.

Python
word = "  héllo  ".strip()
print(len(word.encode()))
print(len(word))
print(word.upper())
print(word.count("l"))
Rust
fn main() {
    let word = "  héllo  ".trim();
    println!("{}", word.len());
    println!("{}", word.chars().count());
    println!("{}", word.to_uppercase());
    println!("{}", word.matches('l').count());
}
Output
6
5
HÉLLO
2

Where the Python analogy breaks

Cheat card

PythonRust
x = 5 · ratio = 0.5let x: i32 = 5; · let ratio: f64 = 0.5;
n = 200 # 0..255let n: u8 = 200;
big = 10_000_000_000let big: i64 = 10_000_000_000;
i = len(items) # index typelet i: usize = items.len();
7 / 2 # 3.5 · 7 // 2 # 37.0 / 2.0 · 7 / 2 // 3, cuts toward zero
float(x) · int(x)x as f64 · x as i32
len(s) # characterss.len() // bytes · s.chars().count()
s.upper() · s.strip()s.to_uppercase() · s.trim()
sub in s · s.split(",")s.contains(sub) · s.split(',')
f"{a}!" · s += "!"format!("{a}!") · s.push_str("!")
s = "hi"let s: &str = "hi"; // borrowed view · let mut s = String::from("hi"); // owned
True · c = "x"true · let c: char = 'x';

← Hello, variables and mut Functions and expressions →