0
0
Rustprogramming~5 mins

Expression evaluation in Rust

Choose your learning style9 modes available
Introduction

Expression evaluation means calculating the result of a math or logic statement in code. It helps the computer decide what value to use next.

When you want to add, subtract, multiply, or divide numbers.
When you need to compare two values to make decisions.
When you want to combine values using logical operations like AND or OR.
When you want to store the result of a calculation in a variable.
When you want to print the result of a calculation to the screen.
Syntax
Rust
let result = expression;

An expression can be a math operation like 5 + 3 or a comparison like 4 > 2.

The result of the expression is stored in a variable using let.

Examples
Adds 5 and 3, then stores 8 in sum.
Rust
let sum = 5 + 3;
Checks if 10 is greater than 7, stores true in is_greater.
Rust
let is_greater = 10 > 7;
First adds 4 and 2, then multiplies the result by 3, stores 18 in combined.
Rust
let combined = (4 + 2) * 3;
Sample Program

This program calculates and prints the sum, difference, product, and quotient of two numbers. It also checks if one number is greater than the other.

Rust
fn main() {
    let a = 10;
    let b = 5;
    let sum = a + b;
    let difference = a - b;
    let product = a * b;
    let quotient = a / b;
    let is_a_greater = a > b;

    println!("Sum: {}", sum);
    println!("Difference: {}", difference);
    println!("Product: {}", product);
    println!("Quotient: {}", quotient);
    println!("Is a greater than b? {}", is_a_greater);
}
OutputSuccess
Important Notes

Rust follows the usual math order: multiplication and division happen before addition and subtraction.

Division between integers gives an integer result (no decimals).

Boolean expressions like comparisons return true or false.

Summary

Expressions calculate values using math or logic.

Use let to save the result of an expression in a variable.

Expressions can be combined and used to make decisions or print results.