Introduction to rule (3)

Time:2020-1-5

In this part, we learn theVariable, data type, function, comment, process controlThese five aspects. The first two parts are introduced, and the last three parts are introduced.

function

Function is common in the rust code. We have seen its main function, main function, which is the entry to the program. We’ve also seen the FN keyword, which is used to declare functions.

Special note: the functions and variables in the rust language are named with lowercase letters and underscores. If you name them in other ways, you will receive a warning.

Function description

The function starts with the FN keyword, followed by the function name and curly braces, and the final curly braces are used to tell the compiler the start and end of the function body. We can also call the function we defined through the function name and parentheses. The defined function can be in front of or behind the main function. Rust doesn’t care where it’s defined, as long as you define it somewhere. Let’s take a simple example:

fn main() {
    println!("Hello, world!");

    another_function();
}

fn another_function() {
    Println! ("another function");
}

Operation result:

cargo run                                          
   Compiling hello_cargo v0.1.0 (/Users/shanpengfei/work/rust-work-space/study/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.57s
     Running `target/debug/hello_cargo`
Hello, world!
Another function

Function parameter

Functions can also be accompanied by some parameters. Functions and parameters together constitute function declarations. When we call a function, we also need to pass the parameters required by the function to it. Let’s take a look at an example:

fn main() {
    another_function(5, 6);
}

fn another_function(x: i32, y: i32) {
    Println! ("X's value is: {}", x);
    Println! ("Y's value is: {}", y);
}

The result of the operation is:

cargo run
   Compiling hello_cargo v0.1.0 (/Users/shanpengfei/work/rust-work-space/study/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.23s
     Running `target/debug/hello_cargo`
The value of x is: 5
The value of y is: 6

The example passes two parameters, 5 to X and 6 to y.

Function bodies can contain statements and expressions

The body of a function is a collection of statements that are combined at the end of an expression. We haven’t used the function at the end of the expression yet, but we’ll see the expression as part of the function body statement. Because rust is an expression based language, which is very important for understanding the rust language. Other languages do not have such a design. Let’s take a look at what kind of design this is.

We have also used statements and expressions in previous chapters. Statement is a collection of operations that do not return a value. Expressions are used to return results. In other languages, we can write code asx = y = 6, making both X and Y 6, but not allowed in the rust language.

The expression return value is unique to the rust language:

  • Some simple mathematical expressions, such as5 + 6It’s an expression that returns 11.
  • Expressions are also part of statements, for example, 6 is a statementlet y = 6Expression with a return value of 6 in.
  • A function call is also an expression.
  • A macro instruction call is also an expression.
  • A new scope created with {} is also an expression.

Just go to the code to see this explanation:

fn main() {
    let x = 5;

    let y = {
        let x = 3;
        x + 1
    };

    Println! ("Y's value is: {}", y);
}

One expression that you can easily see here is:

    {
        let x = 3;
        x + 1
    };

Because in the new scope created by {}, the returned value is 4, which is assigned to the variable y of the let statement. Special note: x + 1 does not have a semicolon at the end, because expressions cannot have a semicolon. If a semicolon is added, the idiom sentence will be automatically converted, and the value of 4 will not be returned, which should be kept in mind.

Function return value

Function can return function evaluation results to the code that calls it. We don’t need to name the return value, but we need to declare the type of the return value after the symbol. In rust, the function return value is the expression at the end of the function body. Of course, we can also use the return keyword to return values, but most functions use the last expression as the return value. Let’s take a look at the example:

fn main() {
    let x = plus_one(5);

    Println! ("X's value is: {}", x);
}

fn plus_one(x: i32) -> i32 {
    x + 1
}

Therelet x = plus_one(5)Equivalent tolet x = 6。 We define the function plus one. Its return value type is I32, and the return value is x + 1. Semicolons cannot be added here.

Notes

All programmers strive to write programs that can be easily understood by others, so they will write some instructions in the program. These notes and instructions will be ignored by the compiler, but they are quite useful for people reading the source code.

In rust, comments start with two slashes until the end of the line.

Process control

In most programming languages, whether to run this part of code depends on whether the condition statement is true or not, and whether to run this part of code continuously depends on whether the condition is true or not. In this part, we will learn the judgment and circulation control processes of rust.

judge

A code that determines which branch to take based on conditions.

if

All the judgment expressions start with if, followed by the conditional expression. Let’s take an example directly:

fn main() {
    let number = 3;

    if number < 5 {
        Println! ("the condition is true");
    } else {
        Println! ("the condition is false");
    }
}

If the variable number is smaller than 5, the print condition is true; otherwise, the print condition is false. You can also consider the match keyword here. Let’s talk about else expression. It mainly provides a code when the condition is false. If you don’t provide else expression, the program will directly skip if expression.

Tips: the expression after if must be of bool type, which is different from ruby and JavaScript.

else if

We can also use the combination of if, else if and else to write the code of multi condition judgment. Let’s take a look at an example directly:

fn main() {
    let number = 6;

    if number % 4 == 0 {
        Println! ("divisible by 4");
    } else if number % 3 == 0 {
        Println! ("divisible by 3");
    } else if number % 2 == 0 {
        Println! ("divisible by 2");
    } else {
        Println! ("cannot be divisible by 2, 3, 4");
    }
}

If too many else if expressions are used, the code will be messy. You can consider the match keyword instead, which will be introduced later.

Use let to receive the value of if

Because if is an expression, you can use let statements to receive the value returned by the if expression. The content is relatively simple. Look at the code directly:

fn main() {
    let condition = true;
    let number = if condition {
        5
    } else {
        6
    };

    Println! ("the result is: {}", number);
}

The result of the operation is:

cargo run
   Compiling hello_cargo v0.1.0 (/Users/shanpengfei/work/rust-work-space/study/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.23s
     Running `target/debug/hello_cargo`
The result is: 5

If and else return values must be of the same type.

loop

About loops, rust provides several methods of loops: loop, while, for. Let’s take a look at them one by one:

loop

The loop keyword tells rust to repeat the following code block until the code explicitly tells rust to stop, for example:

fn main() {
    loop {
        Println! ("repeat printing");
    }
}

This will repeat printingDuplicate printingThese four words, until we use ctrl-c to end the program. You can also use the break keyword in the loop code block to jump out of the loop.

Use let to receive the value of loop

Loop expressions can also return a value like if expressions and assign it to let statements. The expression returned can follow the break keyword. Here’s an example:

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    Println! ("result is {}", result);
}

The result of the code is 20, which is relatively simple.

while

Use the while keyword if conditional judgment is required before executing the loop. When the condition is true, the loop body is executed, and the break keyword can also be used to stop the loop body. Here’s an example:

fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{}!", number);

        number -= 1;
    }

    Println! ("end");
}

Because this content is similar to other languages, it will not be explained here.

for

If you want to traverse an array, use the for keyword. Of course, you can also use the while keyword. First, look at the example of the while keyword:

fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        Println! ("value is: {}", a [index]);

        index += 1;
    }
}

The 5 values in the array will be printed in sequence according to the index, and then see the example of for keyword:

fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a.iter() {
        Println! ("value is: {}", element);
    }
}

The iterator () is used. Of course, the range keyword can also be used, as follows:

fn main() {
    for number in (1..4).rev() {
        println!("{}!", number);
    }
    Println! ("end");
}

The rev () method is to reverse 1, 2, 3, 4 variables 4, 3, 2, 1.

Welcome to Shan Pengfei’s study notes