Skip to content

Rust Functions

Overview

Functions are the basic building blocks of Rust code. This chapter will learn about function definition, parameters, return values, closures, and other concepts.

🔧 Function Basics

Function Definition and Calling

rust
fn main() {
    println!("Hello, world!");

    another_function();
    function_with_parameter(5);
    print_labeled_measurement(5, 'h');

    let x = five();
    println!("The value of x is: {}", x);

    let x = plus_one(5);
    println!("The value of x is: {}", x);
}

fn another_function() {
    println!("Another function.");
}

fn function_with_parameter(x: i32) {
    println!("The value of x is: {}", x);
}

fn print_labeled_measurement(value: i32, unit_label: char) {
    println!("The measurement is: {}{}", value, unit_label);
}

fn five() -> i32 {
    5
}

fn plus_one(x: i32) -> i32 {
    x + 1
}

🔄 Higher-Order Functions

Functions as Parameters

rust
fn add_one(x: i32) -> i32 {
    x + 1
}

fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
    f(arg) + f(arg)
}

fn main() {
    let answer = do_twice(add_one, 5);
    println!("The answer is: {}", answer);
}

📝 Chapter Summary

Functions are a core concept in Rust. Mastering the use of functions is essential for writing Rust programs.


Continue learning: Next chapter - Rust Conditionals

Content is for learning and research only.