Define and call functions
Quick answer
A function names a reusable operation. Instead of repeating instructions in several places, define the operation once with fn and call it by its name whenever needed.
Definition versus execution
The syntax fn name() { ... } defines a function without parameters. The parentheses in name() call it; merely defining it does not execute its body. Functions may be declared before or after main in the same module. Prefer names that describe what the operation does.
fn greet() { println!("Welcome!");}fn main() { greet(); greet();}Expected stdout (not executed):
Welcome!Welcome!Each call executes the body once.
fn line() { println!("---"); }fn report() { line(); println!("Ready"); line();}fn main() { report(); }Expected stdout (not executed):
---Ready---One function can call another; execution returns to the caller afterward.
Common mistake
Writing greet; does not call the function. Use greet() instead.
Try it yourself
Define a function named separator that prints five stars, then call it before and after a message.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Define and call functions — practice quiz
Choose one answer per question, then review the explanation.
What happens when a function is defined but never called?
Can a function declared below main in the same module be called from main?
A function prints one line each time it is called. Two calls produce what?