OneBite.Dev - Coding blog in a bite size

Call A Function With Parameter In Rust

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

In today’s programming world, functions play a vital role, and Rust is no exception. This article aims to teach you how to call a function with a parameter in Rust with an easy-to-understand approach.

Code Snippet: Calling a Function with Parameter in Rust

Let’s start with the code snippet.

fn main() {
    hello("John Doe");
}

fn hello(name: &str) {
    println!("Hello, {}!", name);
}

This is a simple Rust program where a function named “hello” is being called with a string parameter.

Code Explanation for Calling a Function with Parameter in Rust

First, take a look at the main function:

fn main() {
    hello("John Doe");
}

fn main() is the entry point of any Rust program. Inside the main function, we are calling the function hello() with "John Doe" as its argument.

The hello() function is defined as follows:

fn hello(name: &str) {
    println!("Hello, {}!", name);
}

The function definition starts with the fn keyword followed by the function name, which in this case is hello. The parameter name is name and its type is &str, which is a string slice - a reference to a portion of a string.

Inside the hello() function, there’s a println!() macro that prints the string "Hello, {}!" to the console. The {} part is a placeholder for a value, which is replaced with the value of name when the program is run. So, if you call hello("John Doe"), the program will print "Hello, John Doe!".

Each time we call the function hello() with a different parameter, it will greet the name that was put as an argument. In short, the primary focus of this program is to show how you can pass data (parameters) into your functions in Rust to achieve various results.

rust