Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Functions | Rust Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 8 of 50

·rust

Functions

12 minutes

Course progress16%

Functions

Functions are reusable blocks of code. Rust emphasizes function declarations with explicit parameter and return types for clarity and safety.

Function Declaration

fn add(a: i32, b: i32) -> i32 {
    a + b
}

Breakdown:

  • fn keyword declares a function
  • Name: add
  • Parameters: (a: i32, b: i32) with types
  • Return type: -> i32
  • Last expression without semicolon is the return value
  • Parameters and Return Types

    All parameters require type annotations. Return types aren't inferred:

    fn multiply(x: f64, y: f64) -> f64 {
        x * y  // No semicolon—this is the return value
    }
    
    fn print_number(n: i32) {
        // No return type means returns unit ()
        println!(\"Number: {}\", n);
    }  // Implicitly returns ()
    

    Statements vs Expressions

    Statements end with semicolons and don't return values:

    let x = 5;      // Statement
    let y = x + 1;  // Expression (+ returns value)
    

    Expressions don't end with semicolons and return values:

    5 + 6            // Expression returning 11
    {
        let x = 3;
        x + 1        // Expression returning 4
    }
    

    Adding a semicolon turns an expression into a statement, changing the semantics.

    Early Returns

    Use return keyword to exit early:

    fn check_number(n: i32) -> String {
        if n < 0 {
            return String::from(\"Negative\");
        }
        String::from(\"Positive\")
    }
    

    Function Calls

    fn main() {
        let result = add(5, 7);
        println!(\"Sum: {}\", result);  // Sum: 12
    }
    
    fn add(a: i32, b: i32) -> i32 {
        a + b
    }
    
    Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities
    Previous lessonControl FlowContinue to lesson 9Ownership FundamentalsBack to Rust Fundamentals curriculum