Logo

Developer learning path

Rust

Function Parameters and Return Values in Rust

Function Parameters and Return Values

3

#description

Functions are an essential part of any programming language, and Rust is no different. In Rust, functions have parameters and return values.

Here's what you need to know about them:

  1. Function Parameters:

In Rust, function parameters are defined inside the parentheses after the function name. You can specify as many parameters as you need, separated by commas.

Here's an example of a function that takes two parameters:

                    
fn add_numbers(num1: i32, num2: i32) -> i32 {
    num1 + num2
}
                  

In this example, the function add_numbers takes two parameters, num1 and num2, and returns their sum. The data type of the parameters is specified after the parameter name, in this case, i32 which is a 32-bit signed integer data type.

  1. Function Return Values:

In Rust, a function can return a value by using the return keyword followed by the value you want to return. Alternatively, you can return a value without specifying the return keyword. In the example above, there is no return statement, but the function is still returning a value because of the last line in the function, which is an expression that evaluates to num1 + num2.

Here's an example of a function that explicitly returns a value using the return keyword:

                    
fn get_greeting(name: &str) -> String {
    return format!("Hello, {}!", name);
}
                  

In this example, the function get_greeting takes a single parameter, name, which is a reference to a string (&str). It returns a new String object that contains a greeting message with the name parameter.

In Rust, the last statement of a function is what the function returns, so you can often simplify the function by omitting the return keyword and instead using an expression as the last statement.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.