If expressions and boundary decisions
If expressions and boundary decisions
A report labels a mark as meeting the target when it reaches 75. An if expression selects a branch based on a bool condition. Because it can produce a value, you can assign the chosen message instead of printing separately inside each branch.
Write the policy with an inclusive comparison when the threshold itself should qualify. When assigning an if result, both branches must produce compatible types. Else if handles additional decisions, but putting a broad condition first can prevent a narrower one from being reached.
What you’ll learn
- Select a report message with an inclusive threshold.
- Test the values immediately around a decision boundary.
If expressions and boundary decisions in action
Mark: 75
The comparison includes 75, so the first branch produces Target met.
Mark: 75Compare with threshold 75
Both branch values are string slices, which makes the assignment compatible.
Compare with threshold 75Choose Target met
Main prints the selected message once.
Choose Target met
Work through the Rust program
Save the complete source as main.rs in the Rust environment. No standard input is needed.
Rust 2024 · complete program
fn main() {
let score = 75;
let message = if score >= 75 { "Target met" } else { "More practice" };
println!("{message}");
}Expected output
Target metFollow the execution
The comparison includes 75, so the first branch produces Target met. Both branch values are string slices, which makes the assignment compatible. Main prints the selected message once.
Try the complete program in the Rust compiler. For tests, Cargo commands and local files, use the specified local environment.
Try a small variation
Your task: What does the program print if score becomes 74?
Rust 2024 · complete program
fn main() {
let score = 75;
let message = if score >= 75 { "Target met" } else { "More practice" };
println!("{message}");
}Worked answer
It prints More practice because 74 does not meet the inclusive threshold of 75. Check 74, 75 and 76 to review the boundary.
Mistakes and limits to recognize
Conditions must be bool; a nonzero mark is not implicitly true. Avoid using labels such as failure where a neutral next action better expresses the learning policy. The code implements the chosen rule, not a universal grading standard.
Check your understanding
Take the idea into your next program
It prints More practice because 74 does not meet the inclusive threshold of 75. Check 74, 75 and 76 to review the boundary. Conditions must be bool; a nonzero mark is not implicitly true.
Further reading: the official Rust Book on if expressions and boundary decisions.
Reaching the recap and completing the quizzes are separate milestones.