HomeLinuxRust Fundamentals Sequence #5: Capabilities in Rust

Rust Fundamentals Sequence #5: Capabilities in Rust


Like all fashionable programming language, Rust too has features.

The operate that you’re already accustomed to is the important operate. This operate will get known as when this system is launched.

However what about different features? On this article, you may study to make use of features in Rust applications.

The fundamental syntax of a operate

You might already know this based mostly on how we declare the important operate, however let us take a look at the syntax of declaring a operate nonetheless.

// declaring the operate
fn function_name() {
    <assertion(s)>;
}

// calling the operate
function_name();

Let us take a look at a easy operate that prints the string “Hello there!” to the usual output.

fn important() {
    greet();
}

fn greet() {
    println!("Hello there!");
}

📋

Not like C, it doesn’t matter for those who name the operate earlier than declaring or defining it. So long as the stated operate is said someplace, Rust will deal with it.

And as anticipated, it has the next output:

Hello there!

That was easy. Let’s take it to the following degree. Let’s create features that settle for parameter(s) and return worth(s). Neither are mutually unique or inclusive.

Accepting parameters with features

The syntax for a operate that accepts the parameter is as follows:

// declaring the operate
fn function_name(variable_name: kind) {
    <assertion(s)>;
}

// calling the operate
function_name(worth);

You’ll be able to consider the operate parameters as a tuple that’s handed to the operate. It could settle for parameters of a number of knowledge varieties and as many as you would like. So, you aren’t restricted to accepting parameters of the identical kind.

Not like some languages, Rust doesn’t have default arguments. Populating all parameters when calling the operate is obligatory.

Instance: Famished operate

Let us take a look at a program to grasp this higher.

fn important() {
    meals(2, 4);
}

fn meals(theplas: i32, rotis: i32) {
    println!(
        "I'm hungry... I would like {} theplas and {} rotis!",
        theplas, rotis
    );
}

On line 5, I declare a operate known as meals. This operate takes in 2 parameters: theplas and rotis (Names of Indian meals gadgets). I then print the contents of those variables.

From the important operate, I name the meals operate with parameters ‘2’ and ‘4’. Which means that theplas will get assigned the worth ‘2’ and rotis get assigned the worth ‘4’.

Let us take a look at this system output:

I'm hungry... I would like 2 theplas and 4 rotis!

And now I am truly hungry… 😋

Returning values from a operate

Simply as a operate can settle for values within the type of parameters, a operate may return a number of values. The syntax for such a operate is as follows:

// declaring the operate
fn function_name() -> data_type {
    <assertion(s)>;
}

// calling the operate
let x = function_name();

The operate can return a price utilizing both the return key phrase or through the use of an expression as an alternative of an announcement.

Wait! Expression what?

Earlier than you go additional: Statements vs Expressions

It might not match within the circulate of the Rust operate examples however it’s best to perceive the distinction between statements and expressions in Rust and different programming languages.

An announcement is a line of code that ends with a semi-colon and doesn’t consider to some worth. An expression, alternatively, is a line of code that doesn’t finish with a semi-colon and evaluates to some worth.

Let’s perceive that with an instance:

fn important() {
    let a = 873;
    let b = {
        // assertion
        println!("Assigning some worth to a...");

        // expression
        b * 10
    };

    println!("a: {a}");
}

On line 3, I open a code block, inside which I’ve an announcement and an expression. The feedback spotlight which one is which.

The code on the 5th line doesn’t consider to a price and therefore must be ended with a semi-colon. It is a assertion.

The code on the 8th line evaluates to a price. It’s b * 10 which is 873 * 10 and it evaluates to 8730. Since this line doesn’t finish with a semi-colon, that is an expression.

📋

An expression is a helpful approach of returning one thing from a code block. Therefore, it’s an alternate to the return key phrase when a price is returned.
The expressions should not solely used to “return” a price from a operate. As you simply noticed, the worth of `b * 10` was “returned” from the interior scope to the outer scope and it was assigned to the variable `b`. A easy scope is not a operate and the worth of the expression was nonetheless “returned”.

Instance: Shopping for rusted fruits

Let’s perceive how a operate returns a price utilizing an indication.

fn important() {
    println!(
        "If I purchase 2 Kilograms of apples from a fruit vendor, I've to pay {} rupees to them.",
        retail_price(2.0)
    );
    println!(
        "However, if I purchase 30 Kilograms of apples from a fruit vendor, I've 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’ve two features: retail_price and wholesale_price. Each features settle for one parameter and retailer the worth contained in the weight variable. This variable is of kind f64 and the operate signature denotes that an f64 worth is finally returned by the operate.

Each of those features multiply the load of apples bought by a quantity. This quantity represents the present value per Kilogram for apples. Since wholesale purchasers have large orders, logistics are simpler in a approach, the value will be eased a bit.

Aside from the value per Kilogram, the features have yet another distinction. That’s, the retail_price operate returns the product utilizing the return key phrase. Whereas, the wholesale_price operate returns the product utilizing an expression.

If I purchase 2 Kilograms of apples from a fruit vendor, I've to pay 1000 rupees to them.
However, if I purchase 30 Kilograms of apples from a fruit vendor, I've to pay 12000 rupees to them.

The output exhibits that each strategies of returning a price from a operate work as supposed.

Returning a number of values

You’ll be able to have a operate that returns a number of values of various varieties. You’ve gotten many choices, however returning a tuple is the simplest.

Following is an instance:

fn important() {
    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 scholar
    let maths = 84.50;
    let english = 85.00;
    let science = 75.00;
    let sanskrit = 67.25;

    (maths, english, science, sanskrit)
}

The tuple_func returns 4 f64 values, enclosed in a tuple. These values are the marks obtained by a scholar in 4 topics (out of 100).

When the operate known as, this tuple is returned. I can both print the values utilizing tuple_name.0 scheme, however I assumed it finest to destruct the tuple first. That can ease the confusion of which worth is which. And I print the marks utilizing the variables that include values from the destructured tuple.

Following 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 text covers features within the Rust programming language. The “varieties” of features are lined right here:

  • Capabilities that don’t settle for any parameter(s) nor return worth(s)
  • Capabilities that settle for a number of parameters
  • Capabilities that return a number of values again to the caller

You realize what comes subsequent? Conditional statements aka if-else in Relaxation. Keep tuned and revel in studying Rust with It is FOSS.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments