Rust Booleans

Rust Tutorial

🦀 Rust Booleans

In Rust, Boolean values are used for true/false logic, decision-making, and conditions. Rust is very strict with booleans — no jugaad like 0 and 1 here, bhai 😉.

🔹 1. Boolean Data Type (bool)

Rust has only one Boolean type: bool.

fn main() {
let is_rust_fun: bool = true;
let is_bug_free = false;
println!(“{}”, is_rust_fun);
println!(“{}”, is_bug_free);
}

✔ Only two values: true and false


🔹 2. Booleans from Comparisons

Most booleans come from comparison operators.

fn main() {
let a = 10;
let b = 20;
let result = a < b;
println!(“{}”, result); // true
}

Common comparisons:

  • == equal

  • != not equal

  • <, >, <=, >=


🔹 3. Booleans in if Conditions

Rust only allows boolean expressions in conditions.

fn main() {
let age = 19;
if age >= 18 {
println!(“Adult”);
} else {
println!(“Minor”);
}
}

❌ This is NOT allowed:

// if age { } ❌ Rust bolega: bhai ye kya hai?

🔹 4. Logical Operators with Booleans

Operator Meaning
&& AND
`
! NOT
fn main() {
let logged_in = true;
let is_admin = false;
if logged_in && !is_admin {
println!(“User logged in, not admin”);
}
}

🔹 5. Boolean Expressions

Rust treats if as an expression, not just a statement.

fn main() {
let number = 5;
let is_even = if number % 2 == 0 {
true
} else {
false
};println!(“{}”, is_even);
}

Rust way (short and sweet):

let is_even = number % 2 == 0;

Seedhi baat, no bakwaas 😄.


🔹 6. Boolean in Loops

fn main() {
let mut running = true;
while running {
println!(“Program running…”);
running = false;
}
}

🔹 7. Boolean with match

fn main() {
let is_online = true;
match is_online {
true => println!(“User is online”),
false => println!(“User is offline”),
}
}

🔹 8. Boolean vs Integer (Important Difference)

Language Allowed
C / C++ if(1)
Rust if(true)
Rust if(1)

Rust bolta hai: galat hai to galat hai, compromise nahi karega 💪.


🔑 Key Points to Remember

  • bool has only true or false

  • No implicit conversion from int to bool

  • Conditions must be boolean

  • Logical operators work only on booleans

You may also like...