Rust:Rust Operators: Arithmetic, Comparison, and Checked Math
Rust•Operators

Rust Operators: Arithmetic, Comparison, and Checked Math

Learn Rust operators, strict type-matching in expressions, and checked arithmetic.

Syntax

let sum = a + b; let bitwise = flags << 2;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
+, -, *, /ArithmeticRequires operands of identical types.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

fn main() {
    let a: i32 = 25;
    let b: i32 = 4;

    println!("Addition:    {} + {} = {}", a, b, a + b);
    println!("Integer Div: {} / {} = {}", a, b, a / b);
    println!("Float Div:   {:.2}", a as f64 / b as f64);
    println!("Remainder:   {} % {} = {}", a, b, a % b);

    // Bitwise shift
    let bit_shift = 1 << 3;
    println!("1 << 3 =     {}", bit_shift);
}
Expected Output:
Addition:    25 + 4 = 29
Integer Div: 25 / 4 = 6
Float Div:   6.25
Remainder:   25 % 4 = 1
1 << 3 =     8

How It Works: Step-by-Step

  • Lines 5-8: Shows integer division truncation and explicit f64 casting with as.
  • Line 11: Bitwise left shift computes 2^3 = 8.

Key Concepts

  • Rust panics in debug builds if integer arithmetic overflows.
  • Operands must have identical types; no implicit promotions occur.

Common Mistake: Operating on mismatched integer types like i32 + i64

Rust requires explicit type casting with as for all mixed-type expressions.

❌ Incorrect
let a: i32 = 5; let b: i64 = 10; let c = a + b; // Compile Error!
✅ Correct
let c = a as i64 + b;

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler