OneBite.Dev - Coding blog in a bite size

Declare A Function With Return Value In Rust

Code snippet for how to Declare A Function With Return Value In Rust with sample and detail explanation

In Rust programming language, defining and implementing user-defined functions play a significant role in streamlining the code logic and improving reusability. In this article, we will discuss how to declare a function with a return value in Rust.

Code snippet for Declaring a Function with Return Value

fn main() {
    println!("The value of x is: {}", double_value(5));
}

fn double_value(x: i32) -> i32 {
    x * 2
}

Code Explanation for Declaring a Function with Return Value

Let’s break down the code into smaller parts to understand it better.

Firstly, every Rust program has a main function. Here, we’re calling the function double_value which we defined with an input argument 5.

fn main() {
    println!("The value of x is: {}", double_value(5));
}

The next part of the code defines our function double_value. Here’s how the declaration works:

  • fn: This is the keyword to define a function in Rust.
  • double_value: This is the name of the function.
  • (x: i32): These are the input arguments for the function. In this case, x is the argument with i32 as its data type which means it can hold 32-bit signed integers.
fn double_value(x: i32)

The ”-> i32” part of the function signature marks that the function will return a 32-bit signed integer. This is an important aspect of Rust functions. The return value of a function is always the final expression in the function body. In our case, the function will return the value of x * 2;

 -> i32 {
    x * 2
}

As a result, when we run this program, the double_value function will take 5 as an argument, return 10 and then The value of x is: 10 will be printed in the console.

By encapsulating this logic in a function, we can easily change the logic within the function or add more complex operations without affecting the main part of our code. This leads to better readability and maintainability of our Rust programs.

rust