Functions
Part 1 · Rust. Write your own Rust functions with parameters and return values, and learn the difference between expressions and statements.
At Rusty Bean Café, every barista follows the same recipe for a latte. Nobody reinvents it for each customer: they just say “make a latte”. Functions are recipes for your code. You write the steps once, give them a name, and use that name whenever you need them. In this lesson you’ll write your own functions, pass information into them, and get answers back.
Your first function
You’ve already written one function, main. Let’s add another:
fn main() { println!("Opening the café..."); print_welcome(); print_welcome();}
fn print_welcome() { println!("Welcome to Rusty Bean Café!");}Opening the café...Welcome to Rusty Bean Café!Welcome to Rusty Bean Café!fn print_welcome() { ... }defines a function:fn, then a name, then(), then a body in curly braces.- Inside
main,print_welcome();calls the function. Rust jumps into its body, runs it, then comes back and carries on. - We called it twice, so the welcome prints twice. We wrote the steps once and used them twice.
Function names use snake_case, like variables. Notice that print_welcome is defined after main. That’s fine: in Rust, a function can be defined anywhere in the file, before or after it’s used.
Parameters: passing information in
A recipe often needs details: “make a latte in size large”. Functions get details through parameters:
fn main() { greet_customer("Ada"); print_price("Latte", 450);}
fn greet_customer(name: &str) { println!("Hi {name}, what can we get you?");}
fn print_price(item: &str, cents: u32) { println!("{item}: {cents} cents");}Hi Ada, what can we get you?Latte: 450 centsgreet_customer(name: &str)has one parameter calledname, of type&str(text).- When we call
greet_customer("Ada"), the value"Ada"is passed in and becomesnameinside the function. The value you pass in is called an argument. print_pricehas two parameters, separated by a comma. Arguments are matched up in order:"Latte"goes toitem,450goes tocents.
Warning
In Rust, every parameter must have a type. Writing fn greet_customer(name) gives:
error: expected one of `:`, `@`, or `|`, found `)` --> src/main.rs:6:23 |6 | fn greet_customer(name) { | ^ expected one of `:`, `@`, or `|` |help: if this is a parameter name, give it a typeThe help: line tells you the fix: add : TypeName, for example name: &str. Rust never guesses parameter types. That’s a deliberate choice: the function’s first line tells you exactly what it needs.
Return values: getting an answer back
Some recipes produce something you hand back, like a finished drink. A function can return a value. You write the return type after an arrow ->:
fn main() { let total = order_total(450, 2); println!("Two lattes cost {total} cents");}
fn order_total(price: u32, quantity: u32) -> u32 { price * quantity}Two lattes cost 900 cents-> u32says “this function hands back au32”.- The body is just
price * quantity, and there is no semicolon at the end. The last line of a function, without a semicolon, is the value it returns. - In
main,order_total(450, 2)runs the function and becomes900, which we store intotal.
Why no semicolon? To understand that, we need two words: expressions and statements.
Expressions vs. statements
- An expression works something out and produces a value.
450 * 2is an expression (it produces 900). So isorder_total(450, 2), and so is a plain450. - A statement does something but produces no value.
let total = 900;is a statement. It stores a value, but the line itself isn’t a value you can use.
A useful analogy: an expression is a question with an answer (“What’s two lattes?” “900!”). A statement is an instruction (“Put 900 in the total jar.”).
Adding a semicolon turns an expression into a statement. The value is thrown away. So:
price * quantity→ an expression, the value 900, which is returned.price * quantity;→ a statement, the value is thrown away and nothing is returned.
Blocks are expressions too
A block of code in curly braces produces the value of its last expression:
fn main() { let price_with_extra_shot = { let base = 450; let extra_shot = 75; base + extra_shot }; println!("Latte with extra shot: {price_with_extra_shot} cents");}Latte with extra shot: 525 cents- Inside the block, two
letstatements set things up. - The last line,
base + extra_shot, has no semicolon, so the whole block produces525. - That value is stored in
price_with_extra_shot. Note the semicolon after the closing}. That one ends theletstatement.
A function body is the same kind of block, which is why its last expression becomes the return value.
The semicolon mistake
Here is the most common function mistake in Rust, adding a semicolon to the last line:
fn order_total(price: u32, quantity: u32) -> u32 { price * quantity;}The compiler says:
error[E0308]: mismatched types --> src/main.rs:1:46 |1 | fn order_total(price: u32, quantity: u32) -> u32 { | ----------- ^^^ expected `u32`, found `()` | | | implicitly returns `()` as its body has no tail or `return` expression2 | price * quantity; | - help: remove this semicolon to return this value- mismatched types: you promised a
u32but returned something else. - found
():()(an empty tuple, called the unit type) is Rust’s way of saying “nothing”. Because the last line ended in a semicolon, the function returns nothing. - help: remove the semicolon. Exactly right!
Tip
If you see “expected u32, found ()” (or any type versus ()), check the last line of your function for an extra semicolon.
The return keyword
You can also return a value early with the return keyword. It’s handy when you know the answer before reaching the end:
fn main() { println!("{}", discounted_price(450, true)); println!("{}", discounted_price(450, false));}
fn discounted_price(price: u32, has_loyalty_card: bool) -> u32 { if !has_loyalty_card { return price; } price - 50}400450!means “not”. So!has_loyalty_cardistruewhen the customer has no card.- In that case,
return price;leaves the function immediately with the full price. - Otherwise we reach the last line,
price - 50, which is returned with no semicolon and noreturnneeded.
Don’t worry about if yet. It’s the star of the next lesson. Rust style is to use return only for early exits, and to let the last expression be the normal return value.
Note
Functions with no -> return (), the “nothing” value. That’s why print_welcome() doesn’t need a return type: it prints something, but doesn’t hand anything back.
Try it yourself
Write a function price_with_tax(cents: u32) -> u32 that adds 10% tax to a price in cents. Use integer maths: cents + cents / 10. Call it from main for a latte (450) and a croissant (325) and print both results.
Show solution
fn main() { let latte = price_with_tax(450); let croissant = price_with_tax(325); println!("Latte with tax: {latte} cents"); println!("Croissant with tax: {croissant} cents");}
fn price_with_tax(cents: u32) -> u32 { cents + cents / 10}Output:
Latte with tax: 495 centsCroissant with tax: 357 cents325 / 10 is 32 in integer division (the .5 is dropped), so the croissant costs 357. Real tills have rules about rounding, but this is a good start. And notice: no semicolon on the last line of price_with_tax!
Recap
- Define a function with
fn name(params) -> ReturnType { body }and call it withname(arguments). - Every parameter needs a type, like
price: u32. - An expression produces a value. A statement does something and produces no value.
- The last expression in a function body (with no semicolon) is its return value.
returnexits early. - “expected
u32, found()” usually means an extra semicolon on the last line.
What’s next
Our functions can calculate, but they can’t really decide yet. In Control Flow you’ll learn if, loops and a first taste of match.
0 of 35 lessons complete