Writing Rust Functions

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we learn how to write functions in Rust. Functions are declared using the fn keyword, and their arguments are type annotated. The return type, if applicable, is specified after an arrow ->. The final expression in the function serves as the return value, but the return statement can be used to return a value earlier. The lab provides an example of rewriting the FizzBuzz program using functions, demonstrating the use of functions that return boolean values, functions that return the unit type (), and functions without specified return types.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/ControlStructuresGroup(["`Control Structures`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"]) rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/DataTypesGroup -.-> rust/boolean_type("`Boolean Type`") rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/ControlStructuresGroup -.-> rust/for_loop("`for Loop`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("`Traits for Operator Overloading`") subgraph Lab Skills rust/integer_types -.-> lab-99320{{"`Writing Rust Functions`"}} rust/boolean_type -.-> lab-99320{{"`Writing Rust Functions`"}} rust/string_type -.-> lab-99320{{"`Writing Rust Functions`"}} rust/for_loop -.-> lab-99320{{"`Writing Rust Functions`"}} rust/function_syntax -.-> lab-99320{{"`Writing Rust Functions`"}} rust/expressions_statements -.-> lab-99320{{"`Writing Rust Functions`"}} rust/lifetime_specifiers -.-> lab-99320{{"`Writing Rust Functions`"}} rust/operator_overloading -.-> lab-99320{{"`Writing Rust Functions`"}} end

Functions

Functions are declared using the fn keyword. Its arguments are type annotated, just like variables, and, if the function returns a value, the return type must be specified after an arrow ->.

The final expression in the function will be used as return value. Alternatively, the return statement can be used to return a value earlier from within the function, even from inside loops or if statements.

Let's rewrite FizzBuzz using functions!

// Unlike C/C++, there's no restriction on the order of function definitions
fn main() {
    // We can use this function here, and define it somewhere later
    fizzbuzz_to(100);
}

// Function that returns a boolean value
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
    // Corner case, early return
    if rhs == 0 {
        return false;
    }

    // This is an expression, the `return` keyword is not necessary here
    lhs % rhs == 0
}

// Functions that "don't" return a value, actually return the unit type `()`
fn fizzbuzz(n: u32) -> () {
    if is_divisible_by(n, 15) {
        println!("fizzbuzz");
    } else if is_divisible_by(n, 3) {
        println!("fizz");
    } else if is_divisible_by(n, 5) {
        println!("buzz");
    } else {
        println!("{}", n);
    }
}

// When a function returns `()`, the return type can be omitted from the
// signature
fn fizzbuzz_to(n: u32) {
    for n in 1..=n {
        fizzbuzz(n);
    }
}

Summary

Congratulations! You have completed the Functions lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like