bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Rust/Rust Tutorial
Rust•Rust Tutorial

Rust Operators

Operators

Operators are used to perform operations on values and variables.

Rust supports many common operators, like:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators

Arithmetic Operators

Arithmetic operators are used to do basic math:

OperatorNameExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division10 / 25
%Remainder (modulus)10 % 31

Example

fn main() {
  let add = 5 + 3;
  let sub = 10 - 4;
  let mul = 6 * 2;
  let div = 12 / 3;
  let rem = 10 % 3;
  println!("Add: {}", add);
  println!("Sub: {}", sub);
  println!("Mul: {}", mul);
  println!("Div: {}", div);
  println!("Rem: {}", rem);
}

Assignment Operators

Assignment operators are used to assign and update values:

OperatorExampleSame As
=x = 5Assign 5 to x
+=x += 3x = x + 3
-=x -= 2x = x - 2
*=x *= 4x = x * 4
/=x /= 2x = x / 2
%=x %= 2x = x % 2

Example

fn main() {
  let mut x = 10;
  println!("Start: {}", x);
  x += 5;
  println!("After += 5: {}", x);
  x -= 2;
  println!("After -= 2: {}", x);
  x *= 2;
  println!("After *= 2: {}", x);
  x /= 3;
  println!("After /= 3: {}", x);
  x %= 4;
  println!("After %= 4: {}", x);
}

Comparison Operators

Comparison operators compare values and return true or false :

OperatorMeaningExample
==Equal to5 == 5 is true
!=Not equal to5 != 3 is true
>Greater than7 > 3 is true
<Less than2 < 5 is true
>=Greater than or equal to5 >= 5 is true
<=Less than or equal to3 <= 4 is true

Example

fn main() {
  let a = 5;
  let b = 10;
  println!("5 == 10: {}", a == b);
  println!("5 != 10: {}", a != b);
  println!("5 < 10: {}", a < b);
  println!("5 >= 10: {}", a >= b);
}

Logical Operators

Logical operators are used to work with boolean values:

OperatorNameDescription
&&ANDtrue if both values are true
ORtrue if at least one is true
!NOTinverts the boolean value

Example

fn main() {
  let logged_in = true;
  let is_admin = false;
  println!("Is regular user: {}", logged_in && !is_admin);
  println!("Has any access: {}", logged_in || is_admin);
  println!("Not logged in: {}", !logged_in);
}

Previous

Rust Constants

Next

Rust Booleans

This chapter

Overview
20

Lessons

46m

Read time

1. Rust Tutorial2. Rust Introduction3. Rust Get Started4. Rust Syntax5. Rust Output (Print Text)6. Rust Comments7. Rust Variables8. Rust Data Types9. Rust Constants10. Rust Operators11. Rust Booleans12. Rust If .. Else Conditions13. Rust Match14. Rust Loops15. Rust While Loops16. Rust For Loop17. Rust Functions18. Rust Scope19. Rust Strings20. Rust Ownership

On this page

OperatorsArithmetic OperatorsAssignment OperatorsComparison OperatorsLogical Operators