Step 1 of 6
Defining and calling functions
You've been writing one function all along: main. A program can have as many functions as you like. A function is a named block of code that you can run, or call, whenever you need it, by writing its name followed by ().
fn main() {
println!("Match starting");
print_divider();
println!("Round 1");
print_divider();
}
fn print_divider() {
println!("----------");
}
Match starting
----------
Round 1
----------
fn print_divider() { ... }defines the function: its name and what it does. Defining a function doesn't run it.print_divider();calls it: the program jumps into the function, runs its body, then comes back and continues with the line after the call.print_divideris defined belowmain, and that's fine: in Rust, the order of functions in a file doesn't matter.- Function names use
snake_case, like variables. A good name says what the function does, usually with a verb:print_divider,save_game,reset_score.
Why write functions?
- No repetition: write the code once and call it many times. A fix then happens in one place.
- Names explain code:
print_receipt();tells the reader what happens without reading the body. - Small pieces: each function can be understood, and tested, on its own. "This function is too long" is one of the most common code-review comments.
Functions can call functions
Any function can call any other. When a call finishes, the program returns to exactly where it was:
fn main() {
start_round();
start_round();
}
fn start_round() {
println!("Fight!");
cheer();
}
fn cheer() {
println!("The crowd cheers");
}
Fight!
The crowd cheers
Fight!
The crowd cheers
Common mistakes
- Forgetting the
():print_divider;names the function but doesn't call it. Nothing happens, and the compiler warnspath statement with no effect. - A typo in the name:
print_dividr();giveserror[E0425]: cannot find function `print_dividr` in this scope. - Defining a function inside
main's braces by accident: it works, but it can only be used insidemain. Put functions side by side at the top level of the file.
Your task
Fill in the blanks: define a function called cheer and call it twice from main, so the program prints Go, Ferris! two times.
Challenge 2
Fill in the blanks so main calls intro, and intro calls rules. The program should print:
Welcome to the arena
Rule 1: no sandals
Challenge 3
Write a function print_banner that prints these three lines, and call it twice from main (six lines in total):
+--------+
| ARENA |
+--------+