Rust Tutorial
Estimated reading: 4 minutes 57 views

➕ Rust Operators & Expressions – Arithmetic, Logic, Comparison & More

🧲 Introduction – Why Learn Rust Operators?

Operators are essential tools that manipulate data, make decisions, and perform logic in any language. Rust provides a wide range of operators—arithmetic, logical, comparison, assignment, bitwise—and supports rich expressions through type safety and performance-first execution.

🎯 In this guide, you’ll learn:

  • Types of operators in Rust with syntax
  • How expressions work in control flow
  • Practical examples using each operator
  • Rules for operator precedence and associativity

📘 Topics Covered

🧱 Operator Type📖 Purpose
➕ Arithmetic OperatorsBasic math operations
✅ Comparison OperatorsEvaluating equality or relational conditions
🔁 Logical OperatorsBoolean logic and flow control
🔄 Assignment OperatorsAssigning and updating values
🧠 Expressions in RustCombining operations to return values
⚙️ Bitwise OperatorsManipulating individual bits
📈 Operator PrecedenceDetermines evaluation order in complex expressions

➕ Arithmetic Operators

fn main() {
    let a = 10;
    let b = 3;

    println!("Add: {}", a + b);     // 13
    println!("Subtract: {}", a - b); // 7
    println!("Multiply: {}", a * b); // 30
    println!("Divide: {}", a / b);   // 3
    println!("Modulo: {}", a % b);   // 1
}

🧠 Rust ensures no implicit type conversions—you must match types like i32, f64, etc.


✅ Comparison Operators

fn main() {
    let x = 5;
    let y = 10;

    println!("{}", x == y); // false
    println!("{}", x != y); // true
    println!("{}", x < y);  // true
}
OperatorMeaning
==Equal to
!=Not equal to
< >Less / Greater
<= >=Less/Greater or equal

🔍 Returns a bool (true or false)—often used in if, while, and match.


🔁 Logical Operators

fn main() {
    let a = true;
    let b = false;

    println!("AND: {}", a && b); // false
    println!("OR: {}", a || b);  // true
    println!("NOT: {}", !a);     // false
}
OperatorFunction
&&Logical AND
`
!Logical NOT

🧠 Used with bool types to control program flow.


🔄 Assignment Operators

fn main() {
    let mut x = 10;
    x += 5;  // Same as x = x + 5
    println!("x = {}", x); // 15
}
OperatorEquivalent To
=Assignment
+=Add & Assign
-=Subtract & Assign
*=Multiply & Assign
/=Divide & Assign
%=Modulo & Assign

⚙️ Bitwise Operators (Advanced)

Used for low-level programming and binary manipulation.

fn main() {
    let a = 0b1010; // 10
    let b = 0b1100; // 12

    println!("AND: {:b}", a & b); // 1000 (8)
    println!("OR: {:b}", a | b);  // 1110 (14)
    println!("XOR: {:b}", a ^ b); // 0110 (6)
    println!("NOT: {:b}", !a);    // Binary NOT
}
OperatorDescription
&Bitwise AND
``
^Bitwise XOR
!Bitwise NOT
<<Left Shift
>>Right Shift

🧠 Expressions in Rust

In Rust, everything is an expression (except let, const, and type definitions).

let value = if true { 10 } else { 20 };
println!("value: {}", value); // 10

🧠 Even blocks return values:

let result = {
    let x = 2;
    x + 3
};
println!("{}", result); // 5

📈 Operator Precedence

Operators are evaluated based on precedence and associativity:

PrecedenceOperator(s)Associativity
Highest(), [], .Left to Right
High!, - (unary)Right to Left
Medium*, /, %Left to Right
Low+, -Left to Right
Lowest=, +=, &&, etc.Right to Left

Always use parentheses to clarify complex expressions.


📌 Summary – Recap & Next Steps

Rust operators offer type-safe, explicit control over logic, math, and data manipulation. Understanding these is essential for clean and performant systems code.

🔍 Key Takeaways:

  • Arithmetic and comparison operators work similarly to C/Java
  • Logical operators control flow using booleans
  • Bitwise operators are useful in embedded or low-level work
  • Every value-producing statement is an expression
  • Use parentheses to manage precedence clearly

⚙️ Real-World Uses:

  • Writing logic-heavy functions (e.g., parsers, evaluators)
  • Handling boolean flags in CLI apps or configurations
  • Bitmasking in embedded development

❓ Frequently Asked Questions

Are all expressions in Rust type-checked?
✅ Yes. Rust enforces static typing for all operators and expressions at compile time.


Can I override operators in Rust?
✅ Yes. Using traits like Add, Sub, you can implement operator overloading for your types.


Is = an operator or statement in Rust?
✅ It’s part of a statement, but Rust treats many things as expressions. let x = 5; is a statement that ends in an expression.


Why does if return a value in Rust?
✅ Because if is an expression, it can be used to initialize variables based on conditions.


How to safely divide two numbers?
✅ Use checks or return Result to handle divide-by-zero:

fn safe_divide(a: i32, b: i32) -> Option<i32> {
    if b == 0 { None } else { Some(a / b) }
}

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust Operators & Expressions

Or Copy Link

CONTENTS
Scroll to Top