Search⌘ K

And/Or

Explore how to implement logical And (&&) and Or (||) operators in Rust to evaluate boolean expressions. Learn to write functions using these operators for decision making based on age conditions. Understand how combining comparisons with these operators controls program behavior effectively.

We'll cover the following...

Let’s say I’m selling movie tickets and we give a discount to people under 18, as well as to people 65 and older. I’d like to write a function gets_discount(). I can state the requirement in almost-code as age < 18 OR age >= 65. Unfortunately, that OR isn’t real Rust code. Instead, it’s time to introduce the or operator, which is two pipes || (hold shift and hit the backslash key on most keyboards).

Exercise

Implement the gets_discount function correctly to make this program pass.

Rust 1.40.0
fn gets_discount(age: u32) -> bool {
unimplemented!() // replace this!
}
fn main() {
// Kids
assert_eq!(gets_discount(7), true);
assert!(gets_discount(8));
assert!(gets_discount(17));
// Adults
assert_eq!(gets_discount(18), false);
assert!(!gets_discount(30));
assert!(!gets_discount(64));
// Seniors
assert!(gets_discount(65));
assert!(gets_discount(70));
println!("Success!");
}

The or operator is binary, so it takes two values. I’ll explain this the same way I explained or above.

  1. If either or both values are true, it evaluates ...