← Back to Rust Course | Chapter 4: Functions | Lesson 1 of 6

Function Basics

A function is a named box of instructions you can run again and again just by saying its name.

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

markup
fn greet() {
    println!("Hello from a function!");
}

fn main() {
    greet();
}

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

markup
fn print_welcome_message() {
    println!("Welcome to Rust!");
}

fn main() {
    print_welcome_message();
}

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

markup
fn main() {
    say_hello();
}

fn say_hello() {
    println!("Defined after main, but still callable");
}

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

markup
fn cheer() {
    println!("Hooray!");
}

fn main() {
    cheer();
    cheer();
    cheer();
}
Common Mistakes
  1. Forgetting that Rust function names use snake_case, not camelCase like JavaScript or Java.
  2. 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.
  3. Leaving off parentheses when calling a function with no arguments, e.g. writing greet; instead of greet();.
Chapter Summary
  • 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.
  • main is the special function where every executable program begins.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.