Start learning free

LESSON 35 OF 414 · FUNCTIONS I

Why Use Functions in Rust: Reuse and Maintainability

Lesson Read the full explanation

Now that we've learned about functions, let's see why they are so important in our programmers' life:

Consider this: A student named Andy made a mistake and so his teacher told him to write this text 3 times on the whiteboard:

This is Andy
Andy made a mistake
Andy suffers the consequences

We would put this in a simple program like this:

println!("This is Andy");
println!("Andy made a mistake");
println!("Andy suffers the consequences");

println!("This is Andy");
println!("Andy made a mistake");
println!("Andy suffers the consequences");

println!("This is Andy");
println!("Andy made a mistake");
println!("Andy suffers the consequences");

That's manageable. But what if the text consisted of more than 3 lines? And what if the teacher asked Andy to print it for 10 times or 100 times?

You can imagine that our code would get super long while executing 3 different instructions overall.


The story with functions:

This is where functions shine. We can write a function that prints the desired text and then just call the function for as many times as the teacher asks to:

fn print_message() {
	println!("This is Andy");
	println!("Andy made a mistake");
	println!("Andy suffers the consequences");
}

print_message();
print_message();
print_message();

Changing the story:

Need to print the text 3 more times? We call the function 3 more times instead of adding 9 lines to our program.

Need to change the student's name to Mike? We only change it inside the function instead of changing it in the whole program.

fn print_message() {
	println!("This is Mike");
	println!("Mike made a mistake");
	println!("Mike suffers the consequences");
}

print_message();
print_message();
print_message();
print_message();
print_message();

Note:

If you still don't like this code, especially the fact that we have 5 duplicate lines of code: print_message(), you are correct! We will learn how we can make this even better with loops!


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    RUST · FUNCTIONS I

    Why Functions in Rust, explained

    The problem: repeated code

    Suppose a teacher tells a student named Andy to write this text on the whiteboard three times:

    This is Andy
    Andy made a mistake
    Andy suffers the consequences
    

    Without functions, the program repeats the three lines three times:

    println!("This is Andy");
    println!("Andy made a mistake");
    println!("Andy suffers the consequences");
    
    println!("This is Andy");
    println!("Andy made a mistake");
    println!("Andy suffers the consequences");
    
    println!("This is Andy");
    println!("Andy made a mistake");
    println!("Andy suffers the consequences");
    

    Nine lines are manageable. But if the text were longer, or the teacher asked for 10 or 100 copies, the program would grow with every copy while doing the same few things over and over.

    The fix: write it once, call it many times

    A function holds the lines once. You then call it as often as you like:

    fn print_message() {
        println!("This is Andy");
        println!("Andy made a mistake");
        println!("Andy suffers the consequences");
    }
    
    print_message();
    print_message();
    print_message();
    

    This prints the same three lines three times. A fourth copy is one more line, print_message();, instead of three more println! lines.

    Change it in one place

    Functions also make changes cheap. To change the student's name to Mike, edit the body of print_message once. Every call picks up the change:

    fn print_message() {
        println!("This is Mike");
        println!("Mike made a mistake");
        println!("Mike suffers the consequences");
    }
    

    In the repeated version, the same change means editing every copy, and missing one leaves an inconsistent program.

    What functions give you

    • Less repetition. The instructions are written once.
    • One place to fix. A mistake or a change is fixed in the function body and applies to every call.
    • Readable code. A name such as introduce_yourself says what the code does, so a reader does not have to study its lines.
    • Smaller pieces. A big program splits into small functions that are easier to write, test and understand one at a time.

    The five identical calls print_message(); in a row still look repetitive. Loops, which come later, remove that repetition too.

    The exercise, step by step

    The exercise gives a program skeleton. It has a place for a function and a function whose name is mainFunction, which already prints Sorry, I didn't hear you between two comments that say where the introductions go. The goal is to write the introduction once and use it twice.

    1. Define introduce_yourself. Below the comment that marks where the function goes, write fn introduce_yourself() with empty parentheses and braces. No return type is written, so it returns nothing. The name is in snake_case.
    2. Print the first line. Inside the body, println!("My name is Andy");.
    3. Print the second line. On the next line of the body, println!("I love coding");.
    4. Call it the first time. In mainFunction, below the first comment, write introduce_yourself();. Both lines print.
    5. Call it again. Below the last comment, after the "Sorry, I didn't hear you" line, write introduce_yourself(); once more. Both lines print again, without repeating their code.

    The solution in Rust

    // Function goes here:
    fn introduce_yourself() {
        println!("My name is Andy");
        println!("I love coding");
    }
    
    fn mainFunction() {
        // Introduce yourself the first time:
        introduce_yourself();
    
        println!("Sorry, I didn't hear you");
    
        // Introduce yourself again:
        introduce_yourself();
    }
    

    The program prints:

    My name is Andy
    I love coding
    Sorry, I didn't hear you
    My name is Andy
    I love coding
    

    Rust details:

    • Two functions, two roles. introduce_yourself holds the reusable lines. mainFunction decides when they run and what comes between them.
    • The name mainFunction. It is camelCase, but Rust style prefers snake_case. The compiler accepts it and only warns that it should have a snake case name. Keep the name as it is in the skeleton.
    • Calls are statements. introduce_yourself(); needs the parentheses and the semicolon.
    • Comments are ignored. The // lines only mark where the code goes.

    Common mistakes

    • Defining the function but not calling it twice. The two call lines are what produce the two introductions.
    • Calling it in the wrong place. The second call goes after "Sorry, I didn't hear you", so the output order matches the story.
    • Putting both prints in mainFunction. That repeats the code the function was meant to hold.
    • Misspelling the text. Output must match exactly, including capital letters.

    Key takeaways

    • A function lets you write instructions once and run them many times.
    • Changing the function body changes every call.
    • Good function names make code read like a description of what it does.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free