Back to the basics - making choices
In the previous chapter, you learned how to get input from the user, manipulate the input, and display it on the screen.
Another common operation is to make a choice based on the input provided. In Rust, this is done with the if
statement.
Let's start with a small modification to our earlier example.
fn main() { println!("What is your name?"); let input = read_string(); if input == "" { println!("You did not enter your name..."); } else { println!("Your name is: {input}"); } } fn read_string() -> String { let mut input = String::new(); std::io::stdin() .read_line(&mut input) .expect("can not read user input"); let cleaned_input = input.trim().to_string(); cleaned_input }
Note that we've extended the
read_string()
function to trim the whitespace from the input before returning.
The if
statement has this format:
if [comparison] { code to execute when 'true' } else { code to execute when 'false' }
Common comparisons are:
a == b
; a equals ba != b
; a does not equal ba < b
; a is less than ba <= b
; a is less than, or equal to b
The else
block is optional.
The same {
and }
braces are used to group the statements that should be executed when the if
is true or false.
You can chain if
statements together to cover multiple conditions:
fn main() { println!("What is your name?"); let input = read_string(); if input == "" { println!("You did not enter your name..."); } else if input == "Marcel" { println!("{input} is a great name!"); } else { println!("Your name is: {input}"); } } fn read_string() -> String { let mut input = String::new(); std::io::stdin() .read_line(&mut input) .expect("can not read user input"); let cleaned_input = input.trim().to_string(); cleaned_input }
Note that only one of the
if
branches is ever executed.
You can match on multiple conditions in a single if
statement. To do this, separate the conditions with either:
||
for 'or'&&
for 'and'
So imagine we want to print "{} is a great name!"
when the user types either "Marcel" or "marcel", we can use
this if
block:
if input == "" {
println!("You did not enter your name...");
} else if input == "Marcel" || input == "marcel" {
println!("{input} is a great name!");
} else {
println!("Your name is: {input}");
}
Exercise
Add a fourth branch to the
if
block that prints "I love the name {}!" Pick two names for which you want to print this message, and create an appropriate condition for this branch.