How to Create a Function in Rust?

How to Create a Function in Rust?

  • rust
  • 5 mins read

Introduction

In this tutorial, you will learn how to create functions in Rust programming language. It explains step by step, how to create a function, what are the different types of data you can return from a function, how to call a function, how to pass parameters, and how to return values from a function. The tutorial also provides examples of different types of data that can be returned from a function in Rust, to help you understand how to use them in your code. This tutorial is designed for beginners who are just starting with Rust.

Defining a function in Rust

A function in Rust is defined using the fn keyword, followed by the name of the function, a set of parentheses, and a set of curly braces.

fn function_name() {
    // code to be executed
}

For example, the following code defines a function called hello that prints "Hello, world!" when called:

fn hello() {
    println!("Hello, world!");
}

Calling a function in Rust

To call a function, simply use its name followed by a set of parentheses.

fn main() {
    hello();
}

Function Parameters

Functions can also take parameters. The parameters are listed within the parentheses of the function definition, and are separated by commas. The following example takes two parameters, x and y, and returns their sum:

fn add(x: i32, y: i32) -> i32 {
    return x + y;
}

To call the function, simply pass in the values for the parameters:

fn main() {
    let sum = add(5, 10);
    println!("The sum is: {}", sum);
}

Returning values from a function

A function can return a value to the calling code using the return keyword, followed by the value to be returned. The type of the returned value must be specified in the function signature after the arrow ->.

fn add(x: i32, y: i32) -> i32 {
    return x + y;
}
fn main() {
    let sum = add(5, 10);
    println!("The sum is: {}", sum);
}

Rust also has a shorthand way of returning values, the last expression in the function is automatically returned.

fn add(x: i32, y: i32) -> i32 {
    x + y
}
fn main() {
    let sum = add(5, 10);
    println!("The sum is: {}", sum);
}

Create Function in Rust Examples

Example 1: Returning a string

The below example demonstrates how to return a string from a function in Rust. The function get_name() is defined to return a string reference, and the returned string is "Rust". The main function calls the get_name() function and stores the returned string in a variable called name. It then uses the println! macro to print the value of the name variable to the console.

fn get_name<'a>() -> &'a str {
    "Rust"
}

fn main() {
    let name = get_name();
    println!("The name is: {}", name);
}

Output

The name is: Rust

Example 2: Returning a tuple

Below example demonstrates how to return a tuple from a function in Rust. The function get_tuple() is defined to return a tuple containing an integer, a float and a string. The main function calls the get_tuple() function and stores the returned tuple in a variable called tuple. It then uses the println! macro with the format {:?} to print the value of the tuple variable to the console.

fn get_tuple() -> (i32, f32, &'static str) {
    (1, 3.14, "hello")
}

fn main() {
    let tuple = get_tuple();
    println!("The tuple is: {:?}", tuple);
}

Output

The tuple is: (1, 3.14, "hello")

Example 3: Returning an Option<T>

The following example demonstrates how to return Option<T> from a function in Rust. The function divide(x: f32, y: f32) takes two floating point numbers as input and returns an Option<f32>. If y is zero then it returns None else it returns Some(x/y). The main function calls the divide(x: f32, y: f32) function and stores the returned value in a variable called result. It then uses the match statement to check if the returned value is Some or None. If it's Some we print the value, else we print "Cannot divide by zero". This example shows how to return Option<T> from a function and how to handle the cases when the function returns Some or None.

fn divide(x: f32, y: f32) -> Option<f32> {
    if y == 0.0 {
        None
    } else {
        Some(x / y)
    }
}

fn main() {
    let result = divide(10.0, 2.0);
    match result {
        Some(val) => println!("The result is: {}", val),
        None => println!("Cannot divide by zero"),
    }
}

Output

The result is: 5

In this example, we have defined a function divide(x: f32, y: f32) which takes two floating point numbers as input and returns an Option<f32>. If y is zero then we return None else we return Some(x/y). In the main function, we call the divide function and use the match statement to check if the returned value is Some or None. If it's Some we print the value, else we print "Cannot divide by zero".

Conclusion

In this tutorial, we have covered how to create functions in Rust, including how to define a function, how to call a function, how to pass parameters to a function, and how to return values from a function. We also provided examples of returning different types of data from a function in Rust.

Related: