OneBite.Dev - Coding blog in a bite size

Declare A Function With Multiple Parameter In Rust

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

Rust is known for its performance and safety. One integral part of this high-level programming language is the concept of functions, especially those which take multiple parameters.

Code snippet for Declaring a Function with Multiple Parameters in Rust

fn main() {
    print_sum(5, 6);
}

fn print_sum(x: i32, y: i32) {
    println!("Sum is: {}", x + y);
}

Code Explanation for Declaring a Function with Multiple Parameters in Rust

A function declaration in Rust starts with the keyword fn followed by the name of the function. In our example, the function name is print_sum.

Following the function name, we have the function parameters enclosed in parentheses. The function parameters are defined with their names followed by their type, which is defined after a colon. In our example, the function print_sum takes two parameters, x and y, both of which are of type i32 (a 32 bit integer type in Rust).

The function body is enclosed in braces {}. Inside the function print_sum, we have a single statement which prints the sum of the two function parameters. The println! macro is used to print to the console.

The placeholder {} inside the println! statement is where the result of the expression x+y (i.e., the sum of the parameters x and y) will be placed when the program runs.

The main function is the entry point of our Rust program. Here, we call the function print_sum with the arguments 5 and 6. When this program is run, it will output “Sum is: 11” to the console.

With this basic knowledge, you can now declare and use functions with multiple parameters in your Rust programs, which will allow you to write more complex, modular, and maintainable code.

rust