100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Rust

Functions in Rust

Learn how to declare, call, and return values from functions using Rust's fn syntax and expression-based return rules.

Functions & ClosuresBeginner7 min readJul 8, 2026
Analogies

Introduction

Functions are the primary way to organize reusable logic in Rust. Every Rust program starts with a main function, and additional functions can be defined anywhere in a file using the fn keyword. Rust functions use snake_case naming by convention, and the compiler will even warn you if you deviate from it.

🏏

Cricket analogy: The main function is like the toss that starts every match, and fn lets you define extra functions like calculate_run_rate anywhere in the file, with the compiler nudging you toward snake_case names like net_run_rate.

Syntax

rust
fn function_name(param1: Type1, param2: Type2) -> ReturnType {
    // function body
    // last expression (no semicolon) is returned
}

Explanation

Parameters must have explicit type annotations, and the return type is declared after an arrow (->). If a function returns a value, the last line of the body is typically an expression without a trailing semicolon; Rust implicitly returns that expression's value. Adding a semicolon turns the expression into a statement, which evaluates to the unit type () instead. You can also use the return keyword to exit a function early, which is useful inside conditionals or loops.

🏏

Cricket analogy: A calculate_strike_rate function declares runs: u32 with an explicit type and -> f64 for its return; the last line, runs as f64 / balls as f64 with no semicolon, is implicitly returned as the strike rate.

Example

rust
fn add(a: i32, b: i32) -> i32 {
    a + b // no semicolon: this is the return value
}

fn describe(n: i32) -> &'static str {
    if n < 0 {
        return "negative"; // early return
    }
    "non-negative"
}

fn main() {
    let sum = add(3, 4);
    println!("sum = {}", sum);
    println!("7 is {}", describe(7));
    println!("-2 is {}", describe(-2));
}

Output

rust
sum = 7
7 is non-negative
-2 is negative

Key Takeaways

  • Functions are declared with fn and use snake_case names by convention.
  • Parameter types and return types must be explicitly annotated.
  • The last expression without a semicolon is implicitly returned.
  • Adding a semicolon turns an expression into a statement that returns ().
  • The return keyword allows early exits from a function body.

Practice what you learned

Was this page helpful?

Topics covered

#Rust#RustProgrammingStudyNotes#Programming#FunctionsInRust#Functions#Syntax#Explanation#Example#StudyNotes#SkillVeris