OneBite.Dev - Coding blog in a bite size

Declare A Void Function Without Return Value In Rust

Code snippet for how to Declare A Void Function Without Return Value In Rust with sample and detail explanation

In Rust programming, declaring a void function that does not return a value has its own unique syntax and style. This article will guide you through the process of declaring such a function, providing easy-to-understand instructions and code explanations.

Code snippet for Declaring a Void Function Without Return Value in Rust

Before we start, let’s look at a simple code snippet illustrating what a void function in Rust might look like:

fn print_str(s: &str) {
    println!("{}", s);
}

In this snippet, we’ve declared a function called print_str that takes a string slice as an argument and does not return a value.

Code Explanation for Declaring a Void Function Without Return Value in Rust

Step by step, let’s dissect the code snippet to understand how this void function without a return value is declared in Rust:

  1. Function Declaration:

    The function is declared using the fn keyword. After the fn keyword, we have the name of the function, which in this scenario is print_str.

  2. Function Parameters:

    After the function name, we have the function parameters inside parentheses. In our example, the function takes one parameter: a string slice s denoted as &str.

  3. Function Body:

    After the parameters, within the curly braces {}, is the body of the function. This is where the logic of the function resides.

    In this case, our function logic is straightforward – we’re just printing the string passed to the function with the help of println!, a macro that prints to the console.

  4. Return Value:

    In Rust, functions will by default return the value of the final expression in their body. However, in this scenario we see that our function does not return any value. Instead, it merely performs an action (printing the string input to the console). Here, the absence of a -> symbol, which would usually denote the return type, indicates that this function is void - it does not return a value.

In conclusion, declaring a void function without a return value in Rust involves using the fn keyword, specifying the function parameters (if any), writing the function logic in the body, and intentionally omitting a return value.

rust