Lesson 5 of 26
Functions and expressions
A Python function is a block of lines you call, and you give it type hints if you like. A Rust function looks
close, but three things are different, and all three make it easier to read: the types are written down and
checked, the value at the end of the function is the return value, and if and { } blocks can
give back a value instead of only doing something.
Once you know that, most Rust functions read like a Python function with the return moved to the
last line and the ; removed.
Same function, types written down
A Python type hint is a note for other people and for tools. In Rust the types are part of the function
and the compiler checks every call: two arguments, both i32, and the result is an
i32.
Two lines to notice: the parameter types come after a colon, and -> i32 says what the function
gives back. Rust does not care about the order of functions, so add could be below
main.
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3))fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("{}", add(2, 3));
}5return for an early exit
return still exists, and you use it for the same reason as in Python: to leave the function
before the end. The difference is that the last line, with no ;, is the normal way to give back a
value.
Read a Rust function like this: check the return lines first, then the last expression. In
level below, the answer is 0 for small scores, 100 for big ones, and the score itself in between.
def level(score: int) -> int:
if score < 0:
return 0
if score > 100:
return 100
return score
print(level(-5))
print(level(50))
print(level(120))fn level(score: i32) -> i32 {
if score < 0 {
return 0;
}
if score > 100 {
return 100;
}
score
}
fn main() {
println!("{}", level(-5));
println!("{}", level(50));
println!("{}", level(120));
}0
50
100if and blocks give back a value
Python has one expression for a choice: a if cond else b. Rust uses if itself as
an expression, so the two branches sit in braces and the value is whatever the branch ends with. Every branch
must produce the same type.
A plain block { ... } is an expression too. That is the same rule as in a function body: the last
line, with no ;, is the value of the block. In Python you would just write the lines one after
another; in Rust you can keep a temporary value inside a block and let the block hand back the result.
is_member = True
discount = 2 if is_member else 0
base = 10
total = base - discount
print(total)fn main() {
let is_member = true;
let discount = if is_member { 2 } else { 0 };
let total = {
let base = 10;
base - discount
};
println!("{total}");
}8No return type means unit
A function with no -> returns (), called unit. Unit is the type with one
value, also written (), and it plays the part of None: the function does something and
gives nothing back. You will see it in function signatures and in error messages like "expected (),
found i32".
Rust also has no default argument values and no keyword arguments. A Rust function takes every value, in order. When Python code would use defaults, Rust code usually writes a second function with a shorter name, or groups the options in a struct (lesson 9).
def greet(name: str, loud: bool) -> None:
if loud:
print(f"HELLO, {name}!")
else:
print(f"Hello, {name}.")
greet("Ferris", False)
greet("Ferris", True)fn greet(name: &str, loud: bool) {
if loud {
println!("HELLO, {name}!");
} else {
println!("Hello, {name}.");
}
}
fn main() {
greet("Ferris", false);
greet("Ferris", true);
}Hello, Ferris.
HELLO, Ferris!The semicolon that eats the return value
This is the mistake everyone makes once. A ; turns a value into a statement, and a statement
produces (). So the function promises an i32 and gives back unit, and the compiler
stops with E0308, mismatched types.
When you see E0308 on the last line of a function, look for a stray semicolon first. The compiler message even shows the two types it compared.
def double(n: int) -> int:
return n * 2
print(double(4))fn double(n: i32) -> i32 {
n * 2;
}
fn main() {
println!("{}", double(4));
}8Where the Python analogy breaks
- No default values, no keyword arguments, no
*argsor**kwargs. Every call passes every parameter, in order. Where Python uses a default, Rust code often has a second function or takes anOption(lesson 11). - One semicolon changes the result. The last line without
;is the return value. Add a;and the function returns()instead, which doesn't compile if it promised ani32. - The types are checked, not just written down. A Python hint like
x: intdoesn't stopf("5")at run time. In Rust that call doesn't compile. - A function inside a function can't see the outer function's variables. Python's nested functions can read them. In Rust only closures (lesson 8) can.
Cheat card
| Python | Rust |
|---|---|
def add(a: int, b: int) -> int: | fn add(a: i32, b: i32) -> i32 { |
return a + b | a + b // last expression, no semicolon |
return x # early exit | return x; |
def f() -> None: | fn f() { // returns () |
def f(x, y=1): | no default args; write a second function or pass every value |
f(x=1, y=2) | f(1, 2) // no keyword arguments |
a if c else b | if c { a } else { b } |
value = 1 + 2 | let value = { 1 + 2 }; // a block is an expression |
f(1) # call | f(1); |
def main(): ... | fn main() { ... } |
lambda x: x * 2 | |x| x * 2 // closure, lesson 8 |
print(f(1)) | println!("{}", f(1)); |