Rust Notes: Operators in the Rust Language

Rust notes
Operators in the Rust language

Author : Li Juncai (jcLee95) : https://blog.csdn.net/qq_28550263?spm=1001.2101.3001.5343
Email: [email protected]
Address of this article : https://blog.csdn.net/qq_28550263/article/details /131013679


【介绍】:本文讲解 Rust 语言中的运算符。

Previous section: " Previous Section Title " | Next section: " Using Overloading in the Rust Language "


1 Overview

In various programming languages, operators (Operators) are symbols or keywords used to perform various operations. They can be used to manipulate data, perform logical judgments, make assignments, and more. According to their functions and the number of operands, operators can be classified into the following types:

  1. Unary Operators : Unary operators act on a single operand, performing a specific operation or computation on it.
  2. Binary Operators : Binary operators act on two operands to perform a specific operation or computation on them.
  3. Ternary Operator : A ternary operator is a special type of operator that takes three operands and returns the second or third operand depending on the condition of the first operand.

    Note: There is no ternary operator in the Rust language.

  4. Logical Operators : Logical operators are used to perform logical operations such as logical AND, logical OR, and logical NOT.
  5. Comparison Operators : Comparison operators are used to compare the relationship between two values ​​and return a Boolean value (true or false).
  6. Arithmetic Operators : Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, and division, etc.
  7. Bitwise operators : Bitwise operators are used to operate on binary bits, such as bitwise and, bitwise or, bitwise exclusive or, etc.
  8. Index operator : It needs to be used to get the result return from the indexed operand by virtue of the index value.

The above categories overlap. For example, logical operators are also unary operators, and arithmetic operators , index operators, etc. are also binary operators . In the introduction of this article, if it has been explained in the previous category, it will not be repeated in the following article.

2. Unary operators

2.1 About unary operators

Unary operators ( Unary Operators ), also known as unary operators , refer to performing operations on only one expression, which can be any data type in the category of numeric data types. Unary operators in the Rust language include addition (+) , subtraction (-) , **logical not (!)**, and address -of (&) . But on the whole, they can be regarded as unary or binary operators, and the rust language does not provide built-in ternary operators.

2.2 Positive (+) operator

[Note]: + is a it is used to positive , but it is a binary it is used for addition . See also [ plus operator

The plus (+) operator is used to positive without actually changing it.

let a = 10;
let b = +a; // 取 a 的正值(实际上没有变化)
println!("b: {}", b); // 输出: b: 10

2.3 Negative (-) operator

Negative (-) operator is used to negate the operand. For example:

let a = 10;
let b = -a; // 取 a 的负值
println!("b: {}", b); // 输出: b: -10

2.4 Logical NOT (!) operator

The logical NOT (!) operator is used to negate operands of type Boolean . Including the following two situations:

  • If the value of the operand is true, truebecomes false;
  • If the value of the operand is false, falsebecomestrue

For example:

let a = true;
let b = !a;           // 对 a 取逻辑非
println!("b: {}", b); // 输出: b: false

2.5 Increment (++) and decrement (–) operators

Increment (++) and **decrement (–)** operators are used to increment and decrement operands respectively . For example:

// 自增操作
let mut a = 10;
a += 1;               // 等价于 a = a + 1
println!("a: {}", a); // 输出: a: 11

// 自减操作
let mut b = 5;
b -= 1;               // 等价于 b = b - 1
println!("b: {}", b); // 输出: b: 4

2.6 Addressing (&) operator

The address-of (&) operator is used to get the memory address of a variable. For example:

let a = 10;
let b = &a; // 获取变量 a 的内存地址
println!("b: {:?}", b); // 输出: b: 0x7ffc8680d1b8(具体的地址可能不同)

2.7 Dereference (*) operator

The dereference operator *is used to obtain the value pointed to by a reference from a reference type . It allows you to access the actual value stored in the reference type.

For example:

let num = 42;
let num_ref = #

let dereferenced_num = *num_ref;                    // 使用解引用运算符获取引用所指向的值
println!("Dereferenced num: {}", dereferenced_num); // 输出: Dereferenced num: 42

let mut value = 10;
let value_ref = &mut value;

*value_ref = 20;                       // 使用解引用运算符修改引用所指向的值
println!("Modified value: {}", value); // 输出: Modified value: 20

3. Binary operators

3.1 About Binary Operators

Similarly, Binary Operators are operators that act on two operands. In various programming languages, it is generally used to represent a rule that two elements form a third element, and they are often used to perform various operations, such as addition, subtraction, multiplication, division, logical operations, etc.

In the Rust language, the subdivision of binary operators can also be divided into:

  1. Arithmetic operators : used to perform numerical calculations;
  2. Logical operators : used to perform logical operations;
  3. Assignment operator : used to assign the value on the right to the variable on the left;
  4. Comparison operators : used to compare two values ​​and draw conclusions;

3.2 Arithmetic operators

3.2.1 Addition (+) operator

The addition (+) operator is used to add two operands. For example:

let a = 5;
let b = 3;
let c = a + b; // 将 a 和 b 相加
println!("c: {}", c); // 输出: c: 8

3.2.1 Subtraction (-) operator

The subtraction (-) operator is used to subtract the second operand from the first operand. For example:

let a = 5;
let b = 3;
let c = a - b; // 从 a 中减去 b
println!("c: {}", c); // 输出: c: 2

3.2.3 Multiplication (*) operator

The multiplication (*) operator is used to multiply two operands. For example:

let a = 5;
let b = 3;
let c = a * b; // 将 a 和 b 相乘
println!("c: {}", c); // 输出: c: 15

3.2.3 Division (/) operator

The division (/) operator is used to divide the first operand by the second operand. For example:

let a = 10;
let b = 2;
let c = a / b; // 将 a 除以 b
println!("c: {}", c); // 输出: c: 5

3.3 Logical operators

3.3.1 Logical AND (&&)

The logical AND (&&) operator is used to perform a logical AND operation on two operands of type Boolean. For example:

let a = true;
let b = false;
let c = a && b;         // 对 a 和 b 执行逻辑与操作
println!("c: {}", c);   // 输出: c: false

3.3.2 Logical OR (||)

The logical OR (||) operator is used to perform a logical OR operation on two operands of type Boolean. For example:

let a = true;
let b = false;
let c = a || b;        // 对 a 和 b 执行逻辑或操作
println!("c: {}", c);  // 输出: c: true

3.4 Comparison Operators

3.4.1 Equal to (==)

Equality (==) operator is used to check if two operands are equal. For example:

let a = 2;
let b = 2;
let c = a == b;        // 检查 a 和 b 是否相等
println!("c: {}", c);  // 输出: c: true

3.4.2 Not equal to (!=)

The inequality (!=) operator is used to check whether two operands are not equal. For example:

let a = 1;
let b = 3;
let c = a != b;         // 检查 a 和 b 是否不相等
println!("c: {}", c);   // 输出: c: true

3.4.3 Greater Than Operator (>)

The greater than operator (>) is used to check if the left operand is greater than the right operand.

let a = 2;
let b = 1;
let result = a > b;  // 结果为 true

3.4.4 The Less Than Operator (<)

The less than operator (<) is used to check if the left operand is less than the right operand. For example:

let a = 2;
let b = 1;
let result = a < b;    // 结果为 false

3.4.5 Greater than or equal to operator (>=)

The greater than or equal operator (>=) is used to check if the left operand is greater than or equal to the right operand. For example:

let a = 2;
let b = 1;
let result = a >= b;    // 结果为 true

3.4.6 Less than or equal to operator (<=)

The less than or equal operator (<=) is used to check if the left operand is less than or equal to the right operand. For example:

let a = 2;
let b = 1;
let result = a <= b;    // 结果为 false

3.5 Assignment Operators

3.5.1 Basic assignment (=) operator

The assignment (=) operator is used to assign the value on the right to the variable on the left. For example:

let a = 1;             // 将值 1 赋给变量 a

3.5.2 Compound assignment operators (such as +=, -=, *=, /=, etc.)

On the basis of assignment operators, combined with other operators, compound (such as +=, -=, *=, /=, etc.). Compound assignment operators are used to operate the value on the right side of the operator with the variable on the left and assign the result to the variable on the left.

let mut a = 1;
a += 2;               // 等价于 a = a + 2
println!("a: {}", a); // 输出: a: 3

3.6 Bitwise operators

Bitwise operators are used to operate on the binary bits of an integer type and also have two operands, so they can also be regarded as binary operators. In the Rust language, bitwise operators include:

  • Bitwise AND operator (&)
  • bitwise OR operator (|)
  • Bitwise XOR operator (^)
  • Left shift operator (<<)
  • Right shift operator (>>)

3.6.1 Bitwise AND ( &) operator

The bitwise AND operator (&) is used to AND the corresponding binary bits of the two operands, and the result is 1 only when each corresponding bit is 1, otherwise it is 0.

let a = 2;
let b = 3;
let result = a & b;  // 对 a 和 b 的二进制位进行与操作

3.6.2 Bitwise OR ( |) operator

The bitwise OR operator (|) is used to OR the corresponding binary bits of the two operands, and the result is 0 when each corresponding bit is 0, otherwise it is 1.

let a = 5;
let b = 3;
let result = a | b; // 对 a 和 b 的二进制位进行或操作

3.6.3 Bitwise XOR ( ^) operator

The bitwise XOR operator (^) is used to XOR the corresponding binary bits of the two operands, and the result is that each corresponding bit is 0 if they are the same, and 1 if they are different.

let a = 5;
let b = 3;
let result = a ^ b; // 对 a 和 b 的二进制位进行异或操作

3.6.4 Left shift ( <<) operator

The left shift operator (<<) is used to shift the binary bits of the operand to the left by the specified number of bits, and fill the vacated bits on the right with 0.

For example:

let a = 5;            // 二进制表示为 0101
let result = a << 2;  // 将二进制位左移2位,结果为 10100,即 20

3.6.5 Right shift ( >>) operator

The right shift operator (>>) is used to shift the binary bits of the operand to the right by the specified number of bits, and the vacated bits on the left are filled with 0 or a sign bit (depending on the sign of the operand).

For example:

let a = 5;            // 二进制表示为 0101
let result = a >> 1;  // 将二进制位右移1位,结果为 0010,即 2

3.7 Index ( []) operator

The indexing operator []is considered to take two operands: the data structure being indexed and the index value. Among them, the indexed data structure is the left operand, and the index value is the right operand. Indexing operators can be used to access specific elements in a data structure by enclosing the index value within square brackets. The indexed data structure can be of many kinds, such as arrays, vectors, strings, and so on.

3.7.1 Indexing of arrays

Rust arrays have built-in indexing capabilities, and elements can be obtained in bit order through index operators. For example:

let arr = [1, 2, 3, 4, 5];
let element = arr[2];  // 获取索引为2的元素,结果为3
arr[3] = 10;           // 修改索引为3的元素为10

3.7.2 Indexing of vectors

Rust vectors have built-in indexing capabilities, and elements can be obtained in bit order through index operators. For example:

let vec = vec![1, 2, 3, 4, 5];
let element = vec[3];  // 获取索引为3的元素,结果为4
vec[1] = 7;            // 修改索引为1的元素为7

3.7.3 Indexing of strings

str and String are covered in detail in Strings in Rust . Among them, we said that the string type str is an immutable character, and this string type does not support direct indexing through index operators . This is because the str type is a UTF-8 character string with an indeterminate length, direct access through the index may lead to incorrect operations.

Fortunately, there is also a variable string String in the Rust language . The String type supports indexing through index operators. It can access characters in a String using the index operator and passing an integer index. For example:[]

let mut s = String::from("Hello, Rust!");

// 通过索引访问和修改字符
let first_char = s[0];
s[7] = 'W';

println!("First character: {}", first_char);
println!("Modified string: {}", s);

3.8 Call( ()) operator

The call operator () is used to call a function or method. Combining the function or method name with a pair of parentheses allows you to execute the function or method and pass parameters.

For example, we can define a stand-alone function, or define a method in a structure:

fn hello(name: &str) {
    
    
    println!("Hello, {}!", name);
}

struct Person {
    
    
    name: String,
}

impl Person {
    
    
    fn greet(&self) {
    
    
        println!("Hello, {}!", self.name);
    }
}

Then call them via the call operator where you need to use them:

fn main() {
    
    
    hello("Alice"); // 调用函数

    // 调用方法
    let person = Person {
    
    
        name: String::from("Bob"),
    };
    person.greet(); // 输出:Hello, Bob!
}

The call operator () can be used on any callable , including functions , methods , closures , etc. It can take parameters to pass values ​​to the called item .

3.9 Dereferencing the assignment ( *=) operator

The dereference assignment operator ( *=) is a compound operator that is composed of the dereference operator and assignment operator introduced earlier .

*=Used to dereference a mutable reference and assign the new value to the location pointed to by the reference . It dereferences the value on the right and assigns the dereferenced value to the mutable reference on the left . For example:

let num = 42;
let num_ref = &num;

// 使用解引用运算符获取引用所指向的值
let dereferenced_num = *num_ref;
println!("Dereferenced num: {}", dereferenced_num); // 输出: Dereferenced num: 42

let mut value = 10;
let value_ref = &mut value;

// 使用解引用运算符修改引用所指向的值
*value_ref = 20;
println!("Modified value: {}", value); // 输出: Modified value: 20

Guess you like

Origin blog.csdn.net/qq_28550263/article/details/131013679