Logical Operators Part 3
Part of the Fundamentals section of Coddy's Rust journey. Lesson 23 of 75.
When checking multiple conditions, the computer stops checking as soon as it knows the final answer (This is called short-circuit evaluation).
For example:
let x: i32 = 0;
let y: i32 = 5;
let result: bool = x != 0 && y / x > 2;Here x equals 0, therefore it will not evaluate y / x > 2. If we would reverse the order:
let result: bool = y / x > 2 && x != 0;This will result in an error because y will be divided by 0 which is illegal in math.
This technique is used to optimize the evaluation of logical expressions. For example:
let a: i32 = 0;
let b: i32 = 2;
let c: i32 = 3;
let d: i32 = 5;
let result: bool = (a > 0 && b < 2) || (c < -5 && d < 10);In this example b < 2 and d < 10 will not be evaluated because a > 0 and c < -5 are both false.
Challenge
BeginnerLet's create a program to decide if it's a good day for solar panel energy production
Initialize these variables:
is_sunnywith the value truewind_speedwith the value 5.4temperaturewith the value 23solar_panel_outputwith the value 9is_cloudywith the value false
Create one logical expression that checks ALL of these conditions:
- It's sunny
- The wind speed is less than 10
- The solar panel output is less than 15
- The temperature is above 20 OR there are no clouds
Try it yourself
fn main() {
// Initialize variables
// Replace the placeholder values below with the ones from the task
let is_sunny: bool = false;
let wind_speed: f64 = 99.0;
let temperature: i32 = 0;
let solar_panel_output: i32 = 99;
let is_cloudy: bool = true;
// The complete logical expression
// Replace the placeholder below with the full condition
let result: bool = false;
// Don't delete the lines below
println!("Checking conditions for solar energy production...");
println!("1. Is it sunny? {}", is_sunny);
println!("2. Is wind speed safe? {}", (wind_speed < 10.0));
println!("3. Can panels produce more? {}", (solar_panel_output < 15));
println!("4. Is temperature good OR no clouds? {}", (temperature > 20 || !is_cloudy));
println!("\\nFinal result - Good day for solar energy production: {}", result);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic InputPractice on your own: Online Rust compiler