OneBite.Dev - Coding blog in a bite size

Declare A Function With Single Parameter In Rust

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

Rust is a potent and expressive modern programming language that has become quite popular lately. This article takes a closer look at how to declare a function with a single parameter in Rust.

Code Snippet: Declaring a Function with Single Parameter

In Rust, functions are declared using the fn keyword. Here is how you can declare a function with a single parameter:

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

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

Code Explanation: Declaring a Function with Single Parameter

Let’s break this code down step by step to understand it better.

  1. fn main() {: This line is declaring the main function. This is the starting point of any Rust program.

  2. greet("John Doe");: This is a function call to the greet function, and we’re passing "John Doe" as an argument.

  3. fn greet(name: &str) {: This line is declaring a function named greet that takes one parameter name of type &str, which means a string slice. The & symbol means that we’re borrowing the string, not taking ownership of it. This is a concept known as borrowing in Rust. It is a critical component of Rust’s system for managing memory safely and efficiently without a garbage collector.

  4. println!("Hello, {}", name);: This line is printing out a greeting to the console using the println! macro. The {} is a placeholder that gets replaced with the value of name.

So when you run this program, it will output Hello, John Doe.

In Rust, functions are a key part of organizing your code, and understanding how to create and use them is an essential skill. The example above shows you the basics of declaring a function with a single parameter. It’s a foundation you can build on to create more complex and useful functions in your Rust programs.

rust