Start learning free

LESSON 42 OF 679 · FUNCTIONS I

Returning from functions in Rust

Lesson

In the previous lessons, our functions had no return type. This means the function is not returning any value (it returns Rust's empty value, ()).

It's also possible to return a value from a function. For this, we need to specify the return type of the function in the function declaration, after ->.

Inside the function, we can use the return statement to send a value back out of a function.

The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer below):

fn plus_three(num: i32) -> i32 {
	return num + 3;
}

// Inside main function:
let answer = plus_three(5);
println!("{}", answer); // Output: 8

Here, we have the return type i32 instead of no return type. This means that the function returns an i32 value.

plus_three takes an i32 argument for num and returns an i32 value equal to num + 3.


Expression return:

In Rust, a function returns its last expression — written with no semicolon and no return keyword. You only need return to exit early.

fn plus_three(num: i32) -> i32 {
    num + 3   // last expression, no semicolon — this is returned
}

Adding a semicolon (num + 3;) turns it into a statement that returns nothing, so the function would no longer compile. You'll see this semicolon-free return throughout the coding tutorials.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 6
    Ctrl + Enter to check