Day 117 - Functions In Rust

Last time we looked at Variables, Comments and some of the Types in Rust and now its time for funtions in Rust. A function is a piece of code that peforms a task. It can be reused as many times as you want. You can provide some data to it and it can return some data to you.

Functions In Rust

To define a function in Rust, we use fn keyword followed by the function name and paranthesis () and then curly braces {} after that. These {} hold your function code that executes when your function is called.

fn print_a_line() {
    println!("This is a String!");
}

Function Parameters

We can provide the function with parameters in the parathesis. We have to tell the compiler outself what the pratmeter type will be. First we write the parameter name and then after that a colon : and then we specify a type for the parameter.

fn print_a_line(line: &str) {
    println!()
}

Function Return Type

We can also tell the compiler in advance what type of value does the function return will be. We can do so by adding an arrow -> after the paranthesis and then specifying the type.

fn add(a: i32, b: i32) -> i32 {
  a + b
}

Here you see we have a function with two parameters both of which are 32-bit integers and the return type for the function is also a 32-bit integer. Down there we then add two numbers.

But in the above code you may some thing that is may be new to you (it is for me) and that is that we are not using any return keyword here. Functions in Rust will by default return the value of the last line in the function which does not have a semi-colon in the end.

fn add(a: i32, b: i32) -> i32 {
  return a + b;
}

// This function is the same as the above
fn add(a: i32, b: i32) -> i32 {
  a + b
}

But if you add return keyword before something you also have to add a semi-colon at the end too.

That it for the functions of Rust and next we will be covering Loops and Conditionals in Rust and after that we will be taking a look at Owndership which is a new concept to me and is also a unique feature in Rust Programming Language. See you all next time.


zainscizainsci