Function Basics
In this page:
Declaring a Function
Functions are defined with the fn keyword, followed by a name, a parenthesized parameter list, and a body enclosed in curly braces. Calling the function by name executes its body.
Example: Declaring a Function
fn greet() {
println!("Hello from a function!");
}
fn main() {
greet();
}
Login to try C/C++/Java/PHP code in the editor
Function Naming Convention
Rust convention is to name functions and variables in snake_case -- all lowercase words separated by underscores. The compiler will even emit a style warning if you deviate from this.
Example: Function Naming Convention
fn print_welcome_message() {
println!("Welcome to Rust!");
}
fn main() {
print_welcome_message();
}
Login to try C/C++/Java/PHP code in the editor
Functions Can Be Defined in Any Order
Unlike some scripting languages, Rust does not require a function to be defined before it is used in the source file -- the compiler resolves all function definitions in a file before checking calls.
Example: Functions Can Be Defined in Any Order
fn main() {
say_hello();
}
fn say_hello() {
println!("Defined after main, but still callable");
}
Login to try C/C++/Java/PHP code in the editor
Calling Functions Multiple Times
Once defined, a function can be called as many times as needed, from as many places as needed, making it a reusable unit of behavior.
Example: Calling Functions Multiple Times
fn cheer() {
println!("Hooray!");
}
fn main() {
cheer();
cheer();
cheer();
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting that Rust function names use
snake_case, notcamelCaselike JavaScript or Java. - Trying to call a function before it is defined in a way that assumes source order matters -- Rust allows calling functions defined later in the same file.
- Leaving off parentheses when calling a function with no arguments, e.g. writing
greet;instead ofgreet();.
- Functions are declared with
fn name(parameters) { body }. - Rust function and variable names conventionally use
snake_case. - Functions can be defined in any order within a file; Rust does not require forward declarations.
mainis the special function where every executable program begins.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: