A temperature display needs two labels: below zero, or zero and above. We will classify a single integer, then change it to check the boundary.
Rust uses if to run a block when its condition is true. An else block supplies the alternative when the condition is false.[1]
Choose a branch
Tested on Linux ARM64 with rustc 1.99.1 and Cargo 1.99.1. Create a fresh project, then open its decisions folder in your editor and terminal.
cargo new --vcs none decisions
$ cargo new --vcs none decisions Creating binary (application) `decisions` packagenote: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.htmlexit=0
Replace src/main.rs with this complete programme. The value is fixed in the source, so each run uses the same input until you edit it.
fn main() { let temperature: i32 = -2; if temperature < 0 { println!("Below zero"); } else { println!("Zero or above"); }}
The comparison temperature < 0 produces a bool. Rust requires a Boolean condition; it does not automatically convert an integer into true or false.[1] Curly braces enclose each branch.
Run the programme from the decisions folder. Each terminal capture includes the executed command and its exit status.
cargo run --quiet
$ cargo run --quietBelow zeroexit=0
With -2, the comparison is true and our programme prints Below zero. The alternative message stays silent. Only one of these two blocks runs.

Zero belongs in the second group: 0 < 0 is false. Our boundary runs with 0 and 3 both printed Zero or above; -1 printed Below zero.
An else block is optional. Without it, a false condition skips the if block and execution continues afterwards.[1] Keep it here so every input receives a label.
A common error: using the number itself
Replace src/main.rs with this deliberately failing version. It removes the comparison and leaves the integer as the condition.
fn main() { let temperature: i32 = -2; if temperature { println!("Below zero"); } else { println!("Zero or above"); }}
Check it without producing an executable.[3]
cargo check --quiet
$ cargo check --quieterror[E0308]: mismatched types --> src/main.rs:4:8 |4 | if temperature { | ^^^^^^^^^^^ expected `bool`, found `i32`For more information about this error, try `rustc --explain E0308`.error: could not compile `decisions` (bin "decisions") due to 1 previous errorexit=101
Our compiler reported expected bool, found i32. E0308 means that the supplied type differs from the expected type.[2]
Restore the comparison temperature < 0. Its true-or-false result answers the question this label needs.
Exercise
Restore the working programme. Set temperature to 0, then to 3, and run after each edit. Predict the label before checking the output.
Next: repeat useful work with loops, ranges and exit conditions.
Browse Rust, one step at a time
Leave a Reply