[Avg. reading time: 8 minutes]
Binary Operators in Rust
Binary operators operate on two operands and produce a result.
Rust groups them into arithmetic, logical, comparison, and bitwise operators.
Arithmetic Operators
Used for numeric calculations.
- Addition
+ - Subtraction
- - Multiplication
* - Division
/ - Modulus
%
Important rule
- Integer division truncates, it does not round
fn main() { let a = 4; let b = 3; println!("Operand 1:{}, Operand 2:{}", a, b); println!("Addition:{}", a + b); println!("Subtraction:{}", a - b); println!("Multiplication:{}", a * b); println!("Division:{}", a / b); println!("Modulus:{}", a % b); }
Logical Operators
Logical operators work on boolean values.
- AND &&
- OR ||
- NOT !
AND and OR are lazy (short-circuiting) operators.
Evaluation rules
- Left-hand side is evaluated first
- Right-hand side may never execute
fn main() { let a = true; let b = false; println!("AND:{}", a && b); println!("OR:{}", a || b); println!("NOT:{}", !a); }
Lazy AND Evaluation
fn expensive_check() -> bool { println!("expensive_check executed"); false } fn main() { let result = false && expensive_check(); println!("Result: {}", result); }
- false && expensive_check()
- LHS is false
- RHS is never evaluated
Lazy OR Evaluation
fn expensive_check() -> bool { println!("expensive_check executed"); true } fn main() { let result = true || expensive_check(); println!("Result: {}", result); }
- RHS is skipped because LHS is already True.
Comparison Operators
fn main() { let a = 2; let b = 3; println!("a > b:{}", a > b); println!("a < b:{}", a < b); println!("a >= b:{}", a >= b); println!("a <= b:{}", a <= b); println!("a == b:{}", a == b); println!("a != b:{}", a != b); }
- Operand types must match
- No implicit type conversions
- Type errors fail at compile time
Bitwise Operators
Bitwise operators work on the binary representation of integers. Instead of using many variables, each bit represents a flag or state.
- Bitwise AND - &
- Bitwise OR - |
- Bitwise NOT - !
- Left Shift Operator - <<
- Right Shift Operator - >>
Common use cases
- Bit flags
- Masking
- Low-level systems programming
- Hardware interaction
| Bit Position | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Component | Pin 7 | Pin 6 | Pin 5 | Pin 4 | Pin 3 | Pin 2 | Pin 1 | Pin 0 |
Example: Need to find out Pin 1 and 3 are On
Bit: 7 6 5 4 3 2 1 0
Pin: 1 0 1 0 1 0 1 0
Pin 1 is ON
Pin 3 is ON
fn main() { let pin: u8 = 0b1010_1110; const MASK: u8 = 0b0000_1010; let result = pin & MASK; println!("masked (binary): {:08b}", result); println!("masked (decimal): {}", result); if pin & (1 << 1) != 0 { println!("Pin 1 is ON"); } else { println!("Pin 1 is OFF"); } if pin & (1 << 3) != 0 { println!("Pin 3 is ON"); } else { println!("Pin 3 is OFF"); } }