How to use Functions in Rust?

Introduction

Rust is a modern low-level language developed by Mozilla Corporation. Functions are the basic building blocks of any programming language. In this article, we will see how to use functions in Rust Programming Language to make effective code. Functions define the code into logical blocks of code. Functions defined once can be called as many times as you require, which increases the code reusability.

Importance of Function in Programming Language

Functions are an essential part of programming. Here are some reasons why functions are important

  • Code Reusability-  Functions allow you to write a piece of code once and use it multiple times in different parts of your program. This saves time and effort and reduces the amount of code you need to write.
  • Modular Programming- Functions help break down a large program into smaller, more manageable modules. This makes the code easier to understand, test, and maintain.
  • Abstraction- Functions allow you to abstract away complex operations and make them easier to use. For example, instead of writing out the code for sorting an array every time you need it, you can create a function that takes an array as input and returns a sorted array as output.
  • Encapsulation- Functions help encapsulate logic and data, which makes your code more secure and less prone to errors. By hiding the implementation details behind a function interface, you can prevent other program parts from accessing and modifying the data directly.
  • Debugging- Functions make it easier to debug your code because you can isolate specific parts of the code and test them independently. This makes it easier to identify and fix errors.

Function Declaration

In Rust Programming Language, we use the fn keyword to declare a function. The function's name should be in snake case as the conventional style for functions, in which all names are in lowercase and separated by an underscore.

Syntax

fn function_name()-> return_type{
    //statements;
    //return_expression
}

Example

fn hello(){                   //function declaration
    println!("Hello Rust");
}

Calling a Function

In Rust Programming Language, we can call any function by entering the function name and parenthesis followed by a semicolon.

Example

 Calling the hello function that we have previously declared.

fn main(){
     hello();   //invoking the function
}

Functions with parameters

Generally, the functions that take arguments or parameters are called functions with parameters. If a function has parameters, then you can pass arguments in the function.

Syntax

fn function_name(parameter_name1:data_type, parameter_name2:data_type)-> return_type{
    // statement
    //return_expression           //function body
}

Example

 Let's create a function that takes the two integer values and returns the sum of both values.

fn add(x:i32, y:i32) -> i32{   // here x and y are parameters
       let z:i32 = x+y;
       z    //returning z
}

Function with return values

In Rust, when functions return some value, that is called a function with return values. If the function does not return anything, that is called a void function. In the function that returns the value, we must declare the return type after the ->. We can return values in two ways-

  • Using return keyword.
  • Without using the return keyword

Using return Keyword

In this  way, we declare the returning value by using the return keyword

Syntax

fn function_name(parameter_name1:data_type, parameter_name2:data_type){
     //statemnts;
     //return return_value;  //returning the value using return keyword
}

Example

 So we will take our previous function named add, which takes two arguments and returns the sum of them.

fn add(x:i32, y:i32) -> i32{   // here x and y are parameters
       let z:i32 = x+y;
       return z;   // returning the variable z with using return keyword
}

Using without return Keyword

In this way, we did not use the return keyword to mention the value the function will return; we simply removed the return keyword and semicolon from the value to be return.

Syntax 

fn function_name() -> return_type{
   //statements
   //return_expression       //here we will not use return keyword and semicolons
}

Example

 So let's take a normal addition function.

fn add(x:i32, y:i32) ->i32{
     let y:i32 = x+y;
     y       //here function will return y
}

Higher-order functions

Rust supports higher-order functions, which take other functions as arguments or return functions as results. This can make your code more concise and expressive.

Example

fn apply_twice<F>(f: F, x: i32) -> i32
where
    F: Fn(i32) -> i32,
{
    f(f(x))
}

fn add_one(x: i32) -> i32 {
    x + 1
}

fn main() {
    let x = 4;
    let y = apply_twice(add_one, x);
    println!("Result is: {}", y); // prints "6"
}

Output

higher-order-function-output

In this example, we have a function apply_twice that takes a function f and an integer x, applies f to x twice, and returns the result. We also have a function add_one that takes an integer and returns the integer plus one. In the main function, we call apply_twice with add_one and x as arguments, which returns 6.

Anonymous functions

Rust allows you to define functions without giving them a name, called anonymous functions or closures. These functions can capture variables from their environment and can be used to implement higher-order functions or to create ad-hoc functions.

Example

fn main() {
    let add = |x, y| x + y;
    let x = 1;
    let y = 2;
    let z = add(x, y);
    println!("{}", z); // prints "3"
}

Output

anonymous-function-output

In this example, we define an anonymous function using the |x, y| x + y syntax, which takes two parameters, x, and y and returns their sum. We then assign this function to the variable add and use it to add x and y together.

Recursion

Rust supports recursion, which is the ability of a function to call itself. Recursion can be used to solve certain problems more elegantly than iterative loops but can also lead to stack overflow errors if not implemented carefully.

Example

fn factorial(n: u32) -> u32 {
    if n == 0 {
        1
    } else {
        n * factorial(n - 1)
    }
}

fn main() {
    let x = 5;
    let y = factorial(x);
    println!("Factorial is: {}", y); // prints "120"
}

Output

recursion-function-output

In this example, we define a function factorial that takes an integer n and returns the factorial of n, which is the product of all integers from 1 to n. We use recursion to calculate the factorial, where the base case is when n is zero, and the recursive case is when n is greater than zero. 

Conclusion

You have made it to the end of the article. So we have seen what the functions are, how to declare them, how to invoke them, and different types of functions based on parameters and return keywords. 

FAQs

Q. What are the functions in Rust programming language?

A. Functions in Rust are the basic building blocks of any programming language. They define code into logical blocks and can be called multiple times to increase code reusability.

Q. How do you declare a function in Rust?

A. In Rust programming language, you use the `fn` keyword to declare a function. The function name should be in snake case.

Q. How do you call a function in Rust?

A. In Rust, you can call any function by entering the function name followed by a parenthesis.

Q. What are functions with parameters in Rust?

A. Functions that take arguments or parameters are called functions with parameters. If a function has parameters, you can pass arguments to the function.

Q. What are anonymous functions in Rust?

A. Anonymous functions, also known as closures, are functions that can be defined without a name and can capture variables from their environment. They are useful for creating ad-hoc functions that are only needed in a small scope.


Similar Articles