Functions and Control Flow

Column introduction: This column serves as an entry-level article on the Rust language, and its purpose is to share programming skills and knowledge about the Rust language. For the Rust language, although the history is not as long as C++ and python, it has many advantages. It not only inherits the running speed of C++, but also has the memory management of Java. Personally, another advantage is the integrated compilation tool cargo.

Daily sharing: Work hard every day, not for anything else, just to have more choices in the future, choose comfortable days, and choose people you like!


Table of contents

function

parameter

control flow

if-expression

loop statement

loop loop statement

cycle label

while loop

for traversal loop

Summarize


function

Function declarations are mentioned in many programming languages, and the function of function should be regarded as an important function in a programming language. Using functions can make functions more standardized and more logical. Increase the readability of the code.

Unlike C++, all function declarations in the Rust language are implemented using the keyword fn. Like the def keyword in Python, this saves us a lot of trouble.

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

The above example is to create a function without parameters, what if we want to create a function with parameters?

parameter

We can define functions that have parameters ( parameters ), which are special variables that are part of the function signature. When a function has parameters (parameters), you can provide concrete values ​​(actual parameters) for those parameters. Technically, these concrete values ​​are called arguments ( arguments ), but in everyday communication, people tend not to distinguish between using parameter and argument to refer to variables in function definitions or specific values ​​​​passed in when calling functions.

fn main() {
  And(3,4);
}
fn And(x:i32, y:i32) ->i32
{
  let num:i32=(x+y);
  println!("x+y: {}",num);
  return num;
}

 The function of a function in the above example is to add two numbers. Two parameters are defined in the function, and the parameter types are both i32. When defining the line parameters, the parameter type must be indicated. At the same time, careful friends should find that there is an arrow symbol behind the function, and it points to the i32 data type.

control flow

Control flow, as the name implies, is a statement that controls the execution of program statements, including conditional statements, loop statements and other statements. Here are some commonly used control statements.

if-expression

ifExpressions allow different branches of code to be executed based on conditions. You provide a condition and say "If the condition is met, run this code; if the condition is not met, don't run this code."

The matching if statement is else or else if. In fact, you can know their functions through the Chinese meaning. It is nothing more than judging whether the conditions are met, and then executing the code according to the judgment.

fn main() {
   let num= And(5,6);
   println!("num: {:?}", num);
}
fn And(x:i32, y:i32) ->i32
{
  let mut number;
  if(x>y)
  {
    println!("x bigger than y");
    number=x-y;
  }
  else if (x==y)
  {
    println!("x equals y");
    number=x;
  }
  else{
    println!("x smaller than y");
    number=y+x;
  }
  return number;
}

 In the example given above, the if, else if, and else statements are used. In addition, each judgment statement is not enclosed in parentheses. Be sure to pay attention to this, it is a bit different from C++. In Rust, the if statement still has many defects. For example, it cannot automatically convert non-Boolean values ​​into Boolean values, that is, the judgment condition can only be Boolean values. Moreover, the if and else statements are too bloated, and the code structure is not beautiful enough. In order to solve this shortcoming, Rust also has a good branch judgment structure called pattern matching (match). It will be introduced later, but here is a simple understanding.

loop statement

A loop statement refers to a way to reuse a piece of code, and it is used a lot, so we must introduce it in detail here.

loop loop statement

The loop loop statement is a bit similar to the usage in MySQL. The loop loop statement is also called an infinite loop statement. You can only jump out when you are sure to jump out of the loop.

fn loops(mut i:i32, mut j:i32)->i32
{
  loop
  {
    if i==j
    {
      break i;
    }
    else if i<j
    {
      //i+=1;
      i=i+1;
      j=j-1;
    }
    else{
      i=i-1;
      j=j+1;
    }
  }
}

 In the loop statement, break i is used; this statement format, which is different from the statement in C++, can terminate the loop statement and return the value of the following expression at the same time. When it comes to the return value, in a function, the return value type of the function must be the same. In addition to break can jump out of the loop, there is another statement - continue. You can end this iteration and enter the next iteration.

cycle label

If there are nested loops, breakand continueapply to the innermost loop at this time. You can optionally specify a loop label ( loop label ) on a loop , and then use the label with breakor continueto have these keywords apply to the labeled loop instead of the innermost loop.

fn main() {
    let mut count = 0;
    'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
            println!("remaining = {remaining}");
            if remaining == 9 {
                break;
            }
            if count == 2 {
                break 'counting_up;
            }
            remaining -= 1;
        }

        count += 1;
    }
    println!("End count = {count}");
}

 The label here can be understood as a variable whose value is "counting_up", and then bound to the loop. As long as the return value of the loop is the value of the variable, the expression is correct and execution starts.

while loop

The while loop statement is the same as in other languages. When the judgment condition is true, execute the loop, otherwise end the loop;

fn main()
{
  While();

}
fn While()
{
  let mut i=0;
  while i!=100
  {
    println!("{}",i);
    i+=1;

  }
}

 This structure removes much of the nesting necessary to use loop, if, elseand , which is much cleaner. breakExecute when the condition is truetrue, otherwise exit the loop. Personally recommend using this.

for traversal loop

As the most common loop, the for loop is used in c++, java and other languages, but the writing format in Rust language is very similar to that in Python.

fn main()
{
  let a:[i32;5]=[1,2,3,4,5];
  for i in a{
    println!("{}",i);
  }

}

Rust also provides a simple data convenience:

fn main()
{
  let a:[i32;5]=[1,2,3,4,5];
  for i in (0..5){
    println!("{}",a[i]);
  }

}

What is used here is a container similar to the range in Python, which can be written quickly, and also provides the reverse function rev.

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

Summarize

Finally, let me introduce the comments of functions. Rust comments are divided into single-line comments (//) and multi-line comments (/* */). This syntax is almost the same as C++. So it is not introduced in the main text. For this article, it mainly introduces some simple keywords and usage in Rust, and the next section enters the study of "ownership". Bye bye! ! !

Guess you like

Origin blog.csdn.net/qq_59931372/article/details/131692453