OneBite.Dev - Coding blog in a bite size

Declare A Simple Function In Rust

Code snippet for how to Declare A Simple Function In Rust with sample and detail explanation

Rust is a system programming language that offers improved memory safety while maintaining high performance. This article will guide you on how to declare a simple function in Rust.

Code snippet for Declaring a Simple Function

Below is a simple and basic way to declare a function in Rust:

fn main() {
  print_greeting("Bobby");
}

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

Code Explanation for Declaring a Simple Function

Let’s break down the code line-by-line to understand it fully.

  1. fn main() {
      print_greeting("Bobby");
    }

    These lines define the main function, which is the entry point to any Rust program. The main function is calling another function named print_greeting with the argument “Bobby”.

  2. fn print_greeting(name: &str) {
      println!("Hello, {}!", name);
    }

    This part of the code defines a function named print_greeting which takes a parameter name of type &str (a string slice) and returns nothing. The function body consists of a single line of code, which prints a greeting message to the console using the println! macro. The {} within the string is a placeholder for a value, which will be replaced by the name received as a parameter in the function call.

In Rust, you declare a function using the fn keyword, followed by the name of the function. After the function name, you include parentheses () within which you declare the input parameters. Each parameter is defined with a name and a type separated by a colon :. If there are multiple parameters, they should be separated by commas. After the parentheses, you use curly brackets {} to contain the functionality of the function - the block of code that will be executed when the function is called. Functions in Rust can also return values, but in our simple example, our function does not return anything.

rust