Introduction
Like any other Programming language, functions are widely used in Rust. And in case you haven't realised, you were already using functions in Rust without knowing.
fn main() {
println!("Hello World");
}
fn main () is nothing but a function.
Why do we use functions? To break down big & complex code into smaller sensible chunks.
Every Rust Program starts from the main function. Then it can call other functions. How? We will see below!
Examples
Rust uses snake_case as a convention to declare functions.
fn main() {
println!("Hello World");
}
fn custom_fn() {
println!("Hello from Custom function.");
}
We have declared a Custom function custom_fn
But when we execute the function, we only see "Hello World"
Why is that? That's because we haven't called the custom_fn
fn main() {
println!("Hello World");
custom_fn();
}
fn custom_fn() {
println!("Hello from Custom function.");
}
Now we will get the desired output.
Parameterized Functions
The function we discussed above is a non-Parameterized function. Below is a Parameterized function.
fn main() {
println!("Hello World");
x_fn(5);
}
fn x_fn(x: i32) {
println!("x = {x}");
}
So what is the difference? I'm sure you have already spotted, and that is we're passing some values while calling our function. The same values are received inside the function and printed in Console.
When values are passed, those are generally called Parameters. When values are received those are called Arguments. Often asked in technical interviews!
In Rust it is also necessary to use the type, in this case i32 when receiving arguments. This is because variables in function are stored in the Stack, and the Compiler instantly gets the types of values to be used in the function.
What are Stacks? We will discuss in another article! For now you can assume it's temporary memory.
Return Values From Functions
Ideally all variables & processes in a function are stored in the Stack, they perform their duties and are destroyed once the function execution is over.
Despite that functions can also return values. Below is the syntax.
fn main() {
let x: i32 = 5;
let y: i32 = 7;
let sum: i32 = sum_of_two_nums(x, y);
println!("Sum of {x} and {y} = {sum}");
}
fn sum_of_two_nums(x: i32, y: i32) -> i32 {
x + y
}
x & y are declared in the main function. Then they're passed as Parameters to the sum_of_two_nums function that returns an integer of type i32
Then we simply add x + y
That's it. Notice we don't use semi-colon ;
This is what differentiates an Expression from a Statement (we will discuss more in a separate article) and Return types are Expressions
The output will be as we exprect:
Sum of 5 and 7 = 12
Conclusion
It is absolutely necessary to master the concept of functions to move forward in Rust (in any Programming language) but I know you'll do it! So see you folks in another informative article, and cheers!