Follow

Follow
Rust Fundamentals - Functions

Photo by Michael Dziedzic on Unsplash

Rust Fundamentals - Functions

Reusable Code Blocks

Shreyas K S's photo
Shreyas K S
ยทOct 5, 2022ยท

3 min read

Play this article

Table of contents

  • Functions
  • Functions In Rust
  • Function Parameters
  • Function With Return Values
  • Nested Functions
  • Statements and Expressions
  • ๐Ÿ’ก Wrapping Things Up

Functions

Functions are the block of code that performs the task. These code blocks can be called and can be reused. Functions can take inputs and return some output.

Consider an example

The light bulb glows when you flip on the switch. Here, the switch will serve as a function that receives the input of flipping that glows a lightbulb as its output.

Functions are a very interesting concept in programming which helps developers in breaking down complex logic into simpler chunks, code reusability and clean code.

Functions In Rust

fn main(){
  // statements 
}

In rust, the entry point of a program is the main function. We can define a function in rust by using the keyword fn followed by a function name and a set of parentheses. Rust uses snake case as the conventional style for function and variable names, in which all letters are lowercase and underscores separate words.

Defining a function in rust

fn function_name(){
  println!("The Missing Semicolon");
}

Function Parameters

Parameters are the special variables that are part of a function's signature. We can provide concrete values to the parameters which are technically anointed as arguments.

fn main() {
    function_with_paramters("Good Morning");
}

fn function_with_paramters(greetings: &str){
    println!("Hello, {greetings}")
}

In the above example function, function_with_paramters greetings is the parameter which takes the definite value as a string slice. When we run this illustration Hello, Good Morning will be printed on the screen.

Also, we need to specify the type of parameters in the function signatures.

Function With Return Values

In rust, functions can return values too. We must specify the return type in the function signature using ->. Within the function body either we can use the return keyword or implicitly return the value from the function.

fn main() {
    let r = function_with_paramters("Good Morning");
    println!("Returned Value : {r}");
}

fn function_with_paramters(greetings: &str) -> &str{
    "Hello, {greetings}" // returned implicitly without `return` keyword
}

fn another_function(x:i32) -> i32{
   let y = 10 * x;
   return y;  // returned value using `return` keyword
}

Nested Functions

Nested functions are equally valid in rust. Regardless, inner functions don't have access to the outer scope. They're just normal functions that are not accessible from outside the function. You could, however, pass the variables to the function as arguments.

Example

fn main() {
    function()
}

fn function() {

    println!("Function");
    fn inner_function() {
        println!("Nested Function 1");

        fn inner_function2() {
            println!("Nested Function 2");
        }

        inner_function2();
    }
    inner_function();
}

Result

Function 
Nested Function 1
Nested Function 2

Statements and Expressions

Function bodies are made up of a series of statements optionally ending in an expression. Rust is an expression-based language, this is an important distinction to understand.

Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value.

fn main() {
    let y = 6; // this is a statement which does not return a value

    let x = {
        let y = y + 10;
        y
    }; // this is an expression
}

๐Ÿ’ก Wrapping Things Up

Functions are a very interesting concept in programming which helps developers in breaking down complex logic into simpler chunks, code reusability and clean code. In this post, we have covered functions in rust, how to declare them, how to use them and parameterized functions. If you run into any issues with any part of this post, please leave a comment so that I can update the content to be more clear. If you like this post please do follow me on Hashnode and subscribe to my newsletter for future updates.

Did you find this article valuable?

Support Shreyas K S by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
ย 
Share this