Start learning free

LESSON 29 OF 348 · FUNCTIONS I

Functions in Rust in Rust

Lesson

A function is a container for a few lines of code that perform a specific task.

Functions allow us to organize our code a lot better by breaking the code into smaller, more manageable chunks that are doing specific things.

Here's how a function definition looks like in Rust:

fn functionName() -> returnType {
	// function body (where all the instructions are written)
}

There are two main components of a function:

1. The function header:

It consists of:

  • returnType which is the type of the value returned by the function
  • functionName is the function's name, a unique identifier we use to refer to the function
  • Parentheses (()). We'll learn more about their use in next lessons


2. The function body:

This is the code that Rust executes whenever the function is called.

It consists of one or more Rust statements placed inside curly brackets {} (where we have our Rust comment).

Here's an example of a function:

fn say_hello() {
	println!("Hello World");
}

The return type of this function is () (the unit type), which means the function is not returning any value. We'll learn more about this in future lessons.

Notice that we indented (added one tab before) our println!("Hello World");.

Indentation is not mandatory like in Python, but we use it to make our code easier to read.


Calling a function

If you copy paste the code we've written above in an editor and run it, you'll notice that nothing is being printed to the console.

That's because a function declaration alone does not ask the code inside the function body to run, it just declares the existence of the function.

The code inside a function body runs, or executes, only when the function is called.

You can call or invoke a function by typing its name followed by parentheses, like this:

// Function declaration:
fn say_hello() {
	println!("Hello World");
}

// Function call:
say_hello(); // Output: Hello World

All of the code inside the function body will be executed every time the function is called.

In our example, each time the function is called it will print out the message Hello World on the dev console.

We can call a function as many times as it is needed.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    Functions in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free