Basic Rust syntax

environment

  • windows 10 64bit

variable

Variables in Rust are immutable by default, which is different from variables in mainstream programming languages ​​currently on the market. However, variables can be made mutable by prefixing the variable name with the keyword mut .

 let total = 100; total = 200;

You can see the prompt cannot assign twice to immutable variable , which means that immutable variables cannot be assigned twice. At this time, there will be no problem if we add mut in front of the variable name, and the total variable can be reassigned multiple times.

 let mut total = 100; total = 200;

One thing to note here is that the mut keyword cannot be used for constants, and the const keyword is used to declare constants. Finally, the type of data must be explicitly specified, such as

 // 无符号32位数const MAX_NUMBER: u32 = 100;

Another important feature of Rust is to hide the shadow . A newly declared variable can overwrite the original variable with the same name.

 let total = 100; let total = total + 1;

The second total in the code will hide the first total , and the total variable used later refers to the second total variable

type of data

In Rust , each value has its corresponding data type, here the data type is divided into two categories, scalar type ( scalar ) and composite type ( compound ). Scalar types include integer types, floating point types, Boolean types, and character types; composite types include tuple and array .

integer type

Divided into signed numbers (starting with the letter i ) and unsigned numbers (starting with the letter u )

For a signed integer type with n bits, it can store all integers in the range from negative 2 to the n-1 power to 2 to the n-1 power minus 1. For example, for i8 , it can store all integers from -128 to 127. For unsigned integer types, all integers in the range from 0 to 2 to the n power minus 1 can be stored. Take u8 as an example, it can store all integers from 0 to 255.

Note that in the above table, there are two special integer types, isize and usize , and their length depends on the target platform on which the program is running. On 64-bit architectures, they are 64-bit, and on 32-bit architectures, they are 32-bit.

 let total:i8 = 200;

Assigning a value to a variable exceeds its scope, and the compiler will report an error

floating point type

Floating-point numbers are numbers with decimals, f32 occupying 32 bits and f64 occupying 64 bits. By default, f64 is used

 let x = 100.0; let y: f32 = 100.0;

Boolean type

The Boolean type in Rust occupies a single byte space, it has only 2 possible values, one is true and the other is false , the type name is bool

 let isFlag: bool = true; let isFlag = false;

character type

In Rust , char is used to represent the character type, which is a single character, represented by single quotes, and strings are represented by double quotes

 let c: char = 'A';

tuple type

A tuple is a combination of multiple values ​​of different types, and the number of elements in a tuple cannot be increased or decreased after it is declared.

 let tup: (char, u32, f64) = ('a', 100, 49.9); // 通过.操作符来访问元组中的元素,元组的索引从0开始println!("{}", tup.0);

array type

In addition to the tuple type, the array type can also combine multiple data types. However, unlike the tuple, the array requires that each element must be of the same type, and once the array is declared, the size cannot be changed at will .

 let arr = [4, 3, 2, 1]; // 通过索引来访问数组中的元素,索引从0开始println!("{}", arr[0]);

function

I have already touched the function before, that is the main function, which is the entry point of the program.

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

Among them, fn is a keyword, indicating that this is a function, main is the function name, and the content inside curly braces {} is the function body, which is where the function logic is implemented. There are no parameters in the main function, see the following example.

 fn add(x: i32, y: i32) { println!("x={}", x); println!("y={}", y); }

There are 2 parameters in parentheses here, both of which are of i32 data type.

In Rust , there are two confusing concepts, statement ( statement ) and expression ( expression ). Statements are instructions that perform an operation but do not return a value, while expressions are instructions that perform a calculation and produce a value as a result.

For example, declaring a variable using let is a statement

 let total: u32 = 100;

Expressions are more common, such as the above literal 100, numerical calculations, function calls, println! macro calls, etc. are all expressions

Next, look at the return value of the function, add --> 返回值类型after the function parameter

 fn add(x: i32, y: i32) -> i32 { println!("x={}", x); println!("y={}", y); }

Finally look at a complete example

 fn add(x: i32, y: i32) -> i32 { println!("x={}", x); println!("y={}", y); return x + y; } fn main() { println!("Hello, world!"); // 函数调用是表达式,将表达式的值赋给num变量let num = add(5, 4); // main函数的返回值是隐藏了,其实就是最后一个表达式的值,本例中是宏调用println!("number={}", num); } 

control flow

In Rust , the logic is shunted through if and else , which is the same as most programming languages

 let num = 99; if(num > 100) { println!("big than 100.\n") } else { println!("small than 100.\n") }

It should be noted that the conditional expression here is expecting a bool type, and Rust will not automatically try to convert the value of non-boolean type to bool type, we must explicitly provide a bool type as the condition in the if expression , which is different from some programming languages.

Through the else if statement, multiple conditional judgments can be realized

 let num = 100; if(num > 100) { println!("big than 100.\n") } else if(num == 100) { println!("equal to 100.\n") } else { println!("small than 100.\n") }

In addition to conditional statements, Rust provides us with three kinds of loops, namely loop , while and for .

Add the loop keyword in front of the code block that needs to be executed in a loop, so that the code block can be executed in an infinite loop

 loop { println!("Hello Rust."); }

To exit the loop, use the break keyword

 let mut counter = 0; loop { println!("Hell Rust."); counter = counter + 1; if(counter > 20) { break; } }

The while loop is to judge the condition before each execution of the loop body, and execute the code fragment if the condition is true. This mode can be realized by combining the loop , if , else and break keywords.

 let mut counter = 100; while (counter > 0) { println!("counter={}", counter); counter = counter - 1; }

The for loop is also a very frequently used type, it is usually used to traverse the elements in the collection.

 let scores = [90, 93, 95, 97, 99, 100]; for score in scores { println!("score={}", score); }

note

In Rust , use // to comment on the table name, write in front of the statement or expression, and use /**/ for multi-line comments.

 let score = 100; // let sc = 0; /* let a = 1; let b = 2; let c = 3; */

In order to make your code more easy to understand, it is recommended that you write more comments. The compiler will ignore comments during compilation, and comments will not affect the performance of the program.

This article is transferred from https://xugaoxiang.com/2023/01/06/rust-foundation/
This site is only for collection, and the copyright belongs to the original author.