What Are The Functions in Rust?

Functions are the building blocks of Rust programming. It allows you to organize your code into reusable blocks for a command-line app, web server, and more. Also helps to keep your logic clean, modular, and readable.

Functions are used to reuse logic, avoid repetition, and structure programs into manageable parts. Rust provides the “fn” keyword to define a function.

Syntax:

fn function_name(parameters) -> return_type {
// function body
}

Explanation of the syntax:

  • fn is the keyword to define a function.
  • we can pass zero or more parameters into the function.
  • The “-> return_type” is optional because it’s used only if the function returns a value.
  • Rust does not use semicolons after return values when using implicit return.

Why Are Functions Important in Rust?

1) Functions help us to stop writing the same code multiple times. Just write at inside a function and call it whenever we need.

For example: If you are calculating tax in multiple parts of your app, write one calculate_tax function and reuse it.

2) Functions break our program into small parts, so each function does a specific task, and our code becomes easier to read and understand.

For example: We can write functions like get_user_input(), validate_data(), and process_payment() types of functions for clean coding.

3) We can test each function independently. if there’s a bug, you only need to check the issued function, not the entire codebase.

For example, We can write tests specifically for is_leap_year() without touching other parts of the code.

4) Functions also help us to separate different parts of our code based on their roles, like input, processing, output, etc.

For example: In a calculator app, set each operation in separate parts, such as:

  • add(a,b)
  • subtract(a,b)
  • multiply(a,b)

A simple Greeting Function Example

fn greet_user(name: &str) {
println!("Hello, {}! Welcome to Rust.", name);
}

fn main() {
greet_user("Aarav");
}

Output:

Hello, Aarav! Welcome to Rust.

See this example, which shows a simple function that takes a string reference and prints a custom greeting.

How to Return Values with Functions?

Rust uses a -> arrow notation to return values and omits the return keyword if the last line is an expression.

Calculate Square Example

fn square(n: i32) -> i32 {
n * n // implicit return
}

fn main() {
let result = square(6);
println!("Square of 6 is: {}", result);
}

Output:

Square of 6 is: 36

Function Parameters and Multiple Arguments

Functions can take multiple inputs, same like other programming languages.

For example: Area of Rectangle

fn calculate_area(length: f64, width: f64) -> f64 {
length * width
}

fn main() {
let area = calculate_area(5.0, 3.2);
println!("Area of rectangle: {} sq units", area);
}

Output:

Area of rectangle: 16 sq units

Rust Function with return Keyword

  • Implicit Return (No return Keyword)
  • Explicit Return (With return Keyword)

a) Implicit Return (No return Keyword)

If the last line is an expression and has no semicolon, so its value is automatically returned. For example:

fn multiply(a: i32, b: i32) -> i32 {
a * b // ← No `return`, no semicolon → this value is returned
}

b) Explicit Return (With return Keyword)

You can use the return keyword to explicitly specify what value you want to return.

fn multiply(a: i32, b: i32) -> i32 {
return a * b; // ← `return` used clearly
}

When to Use Explicit Return in Rust?

We can use return in multiple cases like:

1) To exit early from a function:

fn check_positive(num: i32) -> bool {
if num < 0 {
return false; // Early exit
}
true // Implicit return here
}

2) To make code more readable and intentional, especially for beginners.

3) When using multiple return points in if, else if, or match blocks.

Learn other Topics About Rust Programming

How to Functions Can Call Other Functions?

Now we write Nested Function Calls to call the other functions.

fn double(n: i32) -> i32 {
n * 2
}

fn triple(n: i32) -> i32 {
n * 3
}

fn main() {
let num = 4;
let result = double(triple(num));
println!("Double of triple of {} is {}", num, result);
}

Output:

Double of triple of 4 is 24

Important note:

  • Rust is statically typed, so all the function parameters and return values must have clear types.
  • You can’t omit types in functions.
  • Functions can return multiple values using tuples.

Mini Exercise for You

Task:
Write a Rust function that checks whether a number is even or odd, and prints the result.

Hints:

  • Use % operator
  • Use if-else inside a function
  • Call the function with different numbers

Leave a Comment