Rust Operators
Rust provides several types of operators, including arithmetic, comparison, logical, bitwise, and assignment operators.
Arithmetic operators include:
+for addition-for subtraction*for multiplication/for division%for remainder or modulo
These operators work on numeric types, including integers and floating-point numbers. For example:
let x = 10; let y = 3; let z = x + y; // 13 let w = x / y; // 3 let r = x % y; // 1
Comparison operators include:
==for equality!=for inequality<for less than>for greater than<=for less than or equal to>=for greater than or equal to
These operators compare two values and return a boolean value true or false. For example:
let x = 10; let y = 3; let z = x == y; // false let w = x > y; // true
Logical operators include:
&&for logical AND||for logical OR!for logical NOT
These operators are used to combine boolean expressions and return a boolean value. For example:
let x = true; let y = false; let z = x && y; // false let w = x || y; // true let r = !x; // false
Bitwise operators include:
&for bitwise AND|for bitwise OR^for bitwise XOR<<for left shift>>for right shift
These operators are used to manipulate binary values. They work on integer types and perform bitwise operations on their binary representation. For example:
let x = 0b1010; let y = 0b1100; let z = x & y; // 0b1000 let w = x | y; // 0b1110 let r = x ^ y; // 0b0110 let s = x << 2; // 0b101000
Assignment operators include:
=for simple assignment+=for addition assignment-=for subtraction assignment*=for multiplication assignment/=for division assignment%=for remainder assignment&=for bitwise AND assignment|=for bitwise OR assignment^=for bitwise XOR assignment<<=for left shift assignment>>=for right shift assignment
These operators are used to assign a value to a variable and modify its value in place. For example:
let mut x = 10; x += 5; // x is now 15
