Like any modern programming language, Rust also has functionality.
The job you already know is main
job. This function is called when the program starts.
But what about other jobs? In this article, you will learn how to use functions in Rust programs.
The basic structure of the function
You may already know this based on how we advertise to main
function, but let’s look at the syntax for declaring a function nonetheless.
// declaring the function
fn function_name() {
<statement(s)>;
}
// calling the function
function_name();
Let’s look at a simple function that prints the string “Hello!” to standard output.
fn main() {
greet();
}
fn greet() {
println!("Hi there!");
}
📋
Unlike C, it doesn’t matter if you call the function before declaring it or defining it. As long as the said job is advertised somewhereRust will handle it.
And as expected, it has the following output:
Hi there!
That was simple. Let’s move to the next level. Let’s create functions that accept parameters and return value(s). They are neither mutually exclusive nor exhaustive.
Accept parameters with functions
The syntax for a function that accepts a parameter is as follows:
// declaring the function
fn function_name(variable_name: type) {
<statement(s)>;
}
// calling the function
function_name(value);
You can think of function parameters as a file Graphically linked that is passed to the function. It can accept parameters from as many data types as you want. Therefore, you are not limited to accepting parameters of the same type.
Unlike some languages, Rust default arguments. Filling in all parameters when calling the function is mandatory.
Example: hungry job
Let’s take a look at a program to understand this better.
fn main() {
food(2, 4);
}
fn food(theplas: i32, rotis: i32) {
println!(
"I am hungry... I need {} theplas and {} rotis!",
theplas, rotis
);
}
In line 5, I declare a function called food
. This function takes two parameters: theplas
And rotis
(Indian food names). Then I print the contents of these variables.
from main
function, I pray food
Operate with parameters “2” and “4”. This means that theplas
gets the value “2” and rotis
Get the value “4”.
Let’s look at the program’s output:
I am hungry... I need 2 theplas and 4 rotis!
And now I’m really hungry… 😋
Returns values ​​from a function
Just as a function can accept values ​​in the form of parameters, a function can also return one or more values. The syntax for such a function is as follows:
// declaring the function
fn function_name() -> data_type {
<statement(s)>;
}
// calling the function
let x = function_name();
The function can return a value using either return
keyword or by using an expression in place of a statement.
I am waiting! expression what?
Before you go any further: Phrases vs. Expressions
It may not fit into the flow of Rust function examples but you should understand the difference between statements and expressions in Rust and other programming languages.
A statement is a line of code that ends with a semicolon and Don’t rate it quite. An expression, on the other hand, is a line of code that does not end with a semicolon and evaluates to some value.
Let’s understand it with an example:
fn main() {
let a = 873;
let b = {
// statement
println!("Assigning some value to a...");
// expression
b * 10
};
println!("a: {a}");
}
On line 3, I open a code block, inside which is a statement and an expression. Comments highlight which is which.
The code on the number 5y The line does not evaluate to a value, and therefore must be terminated with a semicolon. This is a statement.
The code on 8y line to value. that it b * 10
that 873 * 10
and is evaluated for 8730
. Since this line does not end with a semicolon, this is an expression.
📋
An expression is an easy way to return something from a block of code. Hence, it is an alternative to return
keyword when a value is returned.
Expressions aren’t just used to “return” a value from a function. As you just saw, the value of `b * 10` has been “returned” from the inner scope to the outer scope and assigned to the variable `b`. The simple range is not a function and the value of the expression still “returns”.
Example: buying rusty fruits
Let’s understand how a function returns a value using a demo.
fn main() {
println!(
"If I buy 2 Kilograms of apples from a fruit vendor, I have to pay {} rupees to them.",
retail_price(2.0)
);
println!(
"But, if I buy 30 Kilograms of apples from a fruit vendor, I have to pay {} rupees to them.",
wholesale_price(30.0)
);
}
fn retail_price(weight: f64) -> f64 {
return weight * 500.0;
}
fn wholesale_price(weight: f64) -> f64 {
weight * 400.0
}
Above I have two functions: retail_price
And wholesale_price
. Both functions accept a single parameter and store the value inside a file weight
Factor. This variable is of type f64
The function signature indicates that the f64
The value is finally returned by the function.
Both functions multiply the weight of apples purchased by a number. This number represents the current price per kilogram of apples. Because wholesale buyers have large orders, the logistics are somehow easier, the price can be eased a little.
Other than the price per kilogram, there is one difference between the functions. This is it retail_price
The function returns the product with return
keyword. While that wholesale_price
The function returns the product using an expression.
If I buy 2 Kilograms of apples from a fruit vendor, I have to pay 1000 rupees to them.
But, if I buy 30 Kilograms of apples from a fruit vendor, I have to pay 12000 rupees to them.
The output shows that both methods of returning a value from a function work as intended.
Return multiple values
You could have a function that returns multiple values ​​of different types. You have many options, but regrouping is the easiest.
Here is an example:
fn main() {
let (maths, english, science, sanskrit) = tuple_func();
println!("Marks obtained in Maths: {maths}");
println!("Marks obtained in English: {english}");
println!("Marks obtained in Science: {science}");
println!("Marks obtained in Sanskrit: {sanskrit}");
}
fn tuple_func() -> (f64, f64, f64, f64) {
// return marks for a student
let maths = 84.50;
let english = 85.00;
let science = 75.00;
let sanskrit = 67.25;
(maths, english, science, sanskrit)
}
the tuple_func
return four f64
values ​​contained in an array. These values ​​are the marks obtained by the student in four subjects (out of 100).
When the function is called, this array is returned. I can either print the values ​​using tuple_name.0
scheme, but I thought it would be best to destroy the tuple first. This will reduce confusion about what value it is. And I print the tags with variables that contain values ​​from the destructed set.
Here is the output I get:
Marks obtained in Maths: 84.5
Marks obtained in English: 85
Marks obtained in Science: 75
Marks obtained in Sanskrit: 67.25
Conclusion
This article discusses functions in the Rust programming language. Job “types” are covered here:
- Functions that accept no parameters and do not return value(s)
- Functions that accept one or more parameters
- Functions that return one or more values ​​to the caller
You know what comes next? Conditional statements also known as if-else in Rest. Stay tuned and have fun learning Rust with FOSS.