Master arithmetic, comparison, logical, and other operators in Walrus
Walrus provides a comprehensive set of operators for arithmetic, comparison, logical operations, and more. This guide covers all available operators and their usage.
// AND operatorprintln(true and true); // trueprintln(true and false); // falseprintln(false and false); // false// OR operatorprintln(true or true); // trueprintln(true or false); // trueprintln(false or false); // false// NOT operatorprintln(not true); // falseprintln(not false); // true
Walrus uses short-circuit evaluation for and and or:
fn expensive_check : { println("This is expensive!"); return true;}// AND short-circuits if first operand is falselet result1 = false and expensive_check();// "This is expensive!" is NOT printed// OR short-circuits if first operand is truelet result2 = true or expensive_check();// "This is expensive!" is NOT printed
Short-circuit evaluation can improve performance by avoiding unnecessary evaluations.
let age = 25;let has_license = true;let has_insurance = true;let can_drive = age >= 16 and has_license and has_insurance;println(can_drive); // truelet is_valid = (age > 18 and has_license) or (age > 21);println(is_valid); // true
let x = 10;x += 5; // x = x + 5 -> 15x -= 3; // x = x - 3 -> 12x *= 2; // x = x * 2 -> 24x /= 4; // x = x / 4 -> 6x %= 4; // x = x % 4 -> 2println(x); // 2
for n in 1..21 { let result = ""; if n % 3 == 0 { result += "Fizz"; } if n % 5 == 0 { result += "Buzz"; } if result == "" { result = str(n); } println(result);}
Even when not strictly necessary, parentheses improve readability:
// Works but less clearlet result = a + b * c - d / e;// Betterlet result = a + (b * c) - (d / e);
Avoid complex compound conditions
Break complex conditions into intermediate variables:
// Hard to readif age >= 18 and (has_license or has_permit) and (has_insurance or has_waiver) and not is_suspended { // ...}// Betterlet is_adult = age >= 18;let can_operate = has_license or has_permit;let is_covered = has_insurance or has_waiver;let is_allowed = is_adult and can_operate and is_covered and not is_suspended;if is_allowed { // ...}
Use appropriate comparison operators
Choose the right operator for your comparison:
// For equalityif count == 0 { } // Goodif not count { } // Unclear for zero check// For rangesif 0 <= value and value <= 100 { } // Goodif value >= 0 and value <= 100 { } // Also clear