Boolean Conditions
Lesson 7 of 48 in Coddy's Rust for C Developers course.
C conditions accept scalar values: zero is false and nonzero is true. Rust requires a bool condition; an integer does not implicitly become a boolean. Write an explicit comparison such as count != 0. The operators &&, ||, and ! mean logical and, or, and not in both languages. && evaluates the right side only if its left side is true; || evaluates the right side only if its left side is false. Use that short-circuit rule to guard an operation such as integer division. Comparisons return bool in Rust. A chained range check needs two comparisons joined by &&; low <= value <= high is not Rust syntax. Rust formats booleans as true and false, whereas C %d prints the promoted boolean as 1 or 0.
C
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int divisor = 0;
bool usable = divisor != 0 && 12 / divisor > 2;
printf("%d %d\n", usable, !usable);
return 0;
}Rust
fn main() {
let divisor: i32 = 0;
let usable = divisor != 0 && 12 / divisor > 2;
println!("{} {}", usable, !usable);
}Replacing a C integer condition with if count does not compile in Rust. State whether you mean nonzero, positive, or a specific bit test.
Challenge
EasyDecide whether a machine may run. Input is temperature door emergency, with temperature from -100 to 200 and both flags either 0 or 1. A closed door is door=1; an emergency is emergency=1. Required API: pub fn temperature_ok(value: i32) -> bool accepts the inclusive interval 10 through 80; pub fn may_run(temperature: i32, door_closed: bool, emergency: bool) -> bool requires an acceptable temperature, a closed door, and no emergency. Output the two results as lowercase Rust booleans separated by one space. Implement the public API in safety.rs. The supplied exercise.rs parses valid input and calls that API. Return the specified text without a trailing newline; the locked driver adds one newline. Do not print from the API. All input values satisfy the stated bounds.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, safety.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod safety;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
assert!(safety::temperature_ok(10));
assert!(safety::temperature_ok(80));
assert!(!safety::temperature_ok(9));
assert!(!safety::temperature_ok(81));
assert!(safety::may_run(47, true, false));
assert!(!safety::may_run(47, false, false));
assert!(!safety::may_run(47, true, true));
assert!(!safety::may_run(-1, true, false));
assert!(safety::may_run(47, true, false));
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap2Decisions and Loops
Boolean ConditionsIf ExpressionsMatch and EnumsLoops and RangesRecap: Charge Gate3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler