Rust Functions

What is a Function in Rust?

A function in Rust is a reusable block of code that performs a specific task. It can accept inputs (parameters), process them, and optionally return a value. Every Rust program starts with a special function called main().

Syntax of a Function

Here is the basic syntax for defining and using a function in Rust:

fn function_name(parameters) -> ReturnType {
// Function body
}
  • fn: Keyword to declare a function.
  • function_name: Name of the function (follows snake_case convention).
  • parameters: Input values the function accepts (optional).
  • -> ReturnType: Specifies the type of value the function returns (optional).
  • Function body: Contains the code to execute.

Defining and Calling a Function

Example 1: Simple Function

fn greet() {
println!("Hello, Rust!");
}

fn main() {
greet(); // Function call
}

Output:

Hello, Rust!

Parameters in Functions

Functions can accept inputs, called parameters, to work with dynamic data.

Example 2: Function with Parameters

fn add(a: i32, b: i32) {
println!("The sum is: {}", a + b);
}

fn main() {
add(5, 10); // Pass arguments 5 and 10
}

Output:

The sum is: 15
  • Parameters: a and b are of type i32.
  • Arguments: Values passed to the function (5 and 10).

Returning Values from Functions

Functions can return a value using the -> syntax to specify the return type. The return keyword is optional for the final expression.

Example 3: Function with a Return Value

fn multiply(a: i32, b: i32) -> i32 {
a * b // The last expression is the return value
}

fn main() {
let result = multiply(4, 5);
println!("The product is: {}", result);
}

Output:

The product is: 20

Functions with Multiple Return Statements

Using the return keyword, functions can have multiple return points.

Example 4: Using return Explicitly

fn check_number(num: i32) -> &'static str {
if num > 0 {
return "Positive";
} else if num < 0 {
return "Negative";
}
"Zero"
}

fn main() {
let result = check_number(-5);
println!("The number is: {}", result);
}

Output:

The number is: Negative

Nested Functions

Rust allows defining functions within other functions, though it’s not common practice.

Example 5: Nested Function

fn main() {
fn inner_function() {
println!("This is a nested function!");
}

inner_function(); // Calling the nested function
}

Output:

This is a nested function!

Using the main() Function

The main() function is the entry point of every Rust program. It cannot take arguments directly or return a value.

Example 6: Basic main() Function

fn main() {
println!("Welcome to the Rust program!");
}

Output:

Welcome to the Rust program!

Generic Functions

Rust supports generic programming, allowing functions to work with different data types.

Example 7: Generic Function

fn display<T>(item: T) 
where T: std::fmt::Debug {
println!("Item: {:?}", item);
}

fn main() {
display(42); // Works with integers
display("Rust!"); // Works with strings
}

Output:

Item: 42  
Item: "Rust!"

Default Values for Parameters

Rust does not support default parameter values directly, but you can achieve similar functionality using optional parameters or overloading.

Functions with No Return Type

A function without a return type (->) returns the () type, representing an empty value.

Example 8: Void Function

fn no_return() {
println!("This function returns nothing!");
}

fn main() {
no_return();
}

Output:

This function returns nothing!

Leave a Comment

BoxofLearn