0
0
Rustprogramming~5 mins

Logical operators in Rust

Choose your learning style9 modes available
Introduction

Logical operators help you combine or change true/false values to make decisions in your program.

Checking if two conditions are both true before continuing.
Deciding if at least one condition is true to run some code.
Making sure a condition is not true before doing something.
Combining multiple checks in a simple way.
Controlling the flow of your program based on multiple true/false tests.
Syntax
Rust
&&  // AND operator
||  // OR operator
!   // NOT operator

&& means both sides must be true.

|| means at least one side is true.

! flips true to false and false to true.

Examples
AND: both must be true, here false because one is false.
Rust
let a = true && false;  // a is false
OR: one true is enough, so result is true.
Rust
let b = true || false;  // b is true
NOT: flips true to false.
Rust
let c = !true;  // c is false
Combining NOT and AND: true AND false is false, NOT false is true.
Rust
let d = !(true && false);  // d is true
Sample Program

This program decides what to do based on weather and umbrella using logical operators.

Rust
fn main() {
    let is_sunny = true;
    let have_umbrella = false;

    if is_sunny && !have_umbrella {
        println!("Go outside without umbrella.");
    } else if !is_sunny && have_umbrella {
        println!("Take umbrella because it's not sunny.");
    } else if !is_sunny && !have_umbrella {
        println!("Stay inside, no umbrella and no sun.");
    } else {
        println!("Go outside with umbrella just in case.");
    }
}
OutputSuccess
Important Notes

Logical operators work with boolean values: true or false.

Use parentheses to group conditions clearly.

Rust uses short-circuit evaluation: it stops checking as soon as the result is known.

Summary

Logical operators combine true/false values to control decisions.

&& means AND, || means OR, and ! means NOT.

They help write clear and simple conditions in your code.