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.i32is the default for a whole number with no annotation.u8,u32,usize: whole numbers that cannot be negative.usizeis the type of lengths and indexes.f64: a float in 64 bits. Python'sfloatis the same thing. Preferf64overf32unless 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.
count = 3
big = 9_000_000_000
ratio = 0.5
letter = "x"
print(count, big, ratio)
print(letter)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}");
}3 9000000000 0.5
xInteger 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 / 2is3in both languages.-7 / 2is-3in Rust, but-7 // 2is-4in 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.
print(7 / 2)
print(7 // 2)fn main() {
println!("{}", 7.0 / 2.0);
println!("{}", 7 / 2);
}3.5
3as: 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.
a = 7
b = 2
ratio = a / b
total = 19.0
rounded = int(total)
print(ratio)
print(rounded)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}");
}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.
name = "Ferris"
message = f"Hello, {name}!"
message += " Welcome."
print(message)
print(len(message))fn main() {
let name: &str = "Ferris";
let mut message = format!("Hello, {name}!");
message.push_str(" Welcome.");
println!("{message}");
println!("{}", message.len());
}Hello, Ferris! Welcome.
23len 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.
word = " héllo ".strip()
print(len(word.encode()))
print(len(word))
print(word.upper())
print(word.count("l"))fn main() {
let word = " héllo ".trim();
println!("{}", word.len());
println!("{}", word.chars().count());
println!("{}", word.to_uppercase());
println!("{}", word.matches('l').count());
}6
5
HÉLLO
2Where the Python analogy breaks
- Integers have a fixed size and can overflow. Python's
intgrows as big as it needs. Au8holds 0 to 255: going past that panics in a debug build and silently wraps around in a release build. - Number types don't mix.
2 * 1.5just works in Python. In Rust, multiplying ani32by anf64doesn't compile until you convert one of them withas. asnever fails, even when the value doesn't fit: ifnis 300,n as u8quietly gives 44. Python numbers have no such limit, so they never lose digits like this.- You can't index a string by position.
s[0]doesn't compile, because a Rust string is UTF-8 bytes and one character can take several bytes. Uses.chars().next()ors.chars().nth(i). - There are two string types. Python has one
str. Rust hasString(owned, can grow) and&str(a borrowed view).
Cheat card
| Python | Rust |
|---|---|
x = 5 · ratio = 0.5 | let x: i32 = 5; · let ratio: f64 = 0.5; |
n = 200 # 0..255 | let n: u8 = 200; |
big = 10_000_000_000 | let big: i64 = 10_000_000_000; |
i = len(items) # index type | let i: usize = items.len(); |
7 / 2 # 3.5 · 7 // 2 # 3 | 7.0 / 2.0 · 7 / 2 // 3, cuts toward zero |
float(x) · int(x) | x as f64 · x as i32 |
len(s) # characters | s.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'; |