📜  锈-运算符

📅  最后修改于: 2020-11-02 04:14:16             🧑  作者: Mango


运算符定义了将在数据上执行的一些函数。运算符作用的数据称为操作数。考虑以下表达式-

7 + 5 = 12

此处,值7、5和12是操作数,而+和=是运算符。

Rust的主要运算符可以分类为-

  • 算术
  • 按位
  • 比较方式
  • 逻辑上
  • 按位
  • 有条件的

算术运算符

假设变量a和b中的值分别为10和5。

显示范例

Sr.No Operator Description Example
1 +(Addition) returns the sum of the operands a+b is 15
2 -(Subtraction) returns the difference of the values a-b is 5
3 * (Multiplication) returns the product of the values a*b is 50
4 / (Division) performs division operation and returns the quotient a / b is 2
5 % (Modulus) performs division operation and returns the remainder a % b is 0

注意-Rust不支持++和-运算符。

关系运算符

关系运算符测试或定义两个实体之间的关系类型。关系运算符用于比较两个或多个值。关系运算符返回布尔值-true或false。

假设A的值为10,B的值为20。

显示范例

Sr.No Operator Description Example
1 > Greater than (A > B) is False
2 < Lesser than (A < B) is True
3 >= Greater than or equal to (A >= B) is False
4 <= Lesser than or equal to (A <= B) is True
5 == Equality (A == B) is fals
6 != Not equal (A != B) is True

逻辑运算符

逻辑运算符用于组合两个或多个条件。逻辑运算符也返回布尔值。假设变量A的值为10,而B为20。

显示范例

Sr.No Operator Description Example
1 && (And) The operator returns true only if all the expressions specified return true (A > 10 && B > 10) is False
2 ||(OR) The operator returns true if at least one of the expressions specified return true (A > 10 || B >10) is True
3 ! (NOT) The operator returns the inverse of the expression’s result. For E.g.: !(>5) returns false !(A >10 ) is True

按位运算符

假设变量A = 2且B = 3。

显示范例

Sr.No Operator Description Example
1 & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. (A & B) is 2
2 | (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. (A | B) is 3
3 ^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. (A ^ B) is 1
4 ! (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. (!B) is -4
5 << (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on. (A << 1) is 4
6 >> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand. (A >> 1) is 1
7 >>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted to the left are always zero. (A >>> 1) is 1