Lesson 3.1 · 10 min
Choosing with if
So far Chatterbox does the same thing every time it runs. A chat program has to react: answer a question one way, a plain message another, and an empty line not at all. That choice is an if, and it gives Chatterbox its first real function: reply.
Adds to Chatterboxreply() answers a message; empty input is ignored.
Two roads
An if looks at a question that has a yes or no answer, and runs one block of code for yes. An optional else block runs for no. Exactly one of the two blocks runs, never both.
The question is any piece of code that comes out as true or false: the booleans from lesson 2.3. Text has a handy question built in, the method is_empty(), which answers "is there nothing in here?".
$ cargo run
(nothing to say)Change message to "hi" and run it again. The other road is taken. There are no brackets around the question, and the curly braces after it are required, even around a single line.
The question must be a bool
Some languages let you write if 1 or if "text" and quietly decide what counts as true. Rust does not guess. The condition must really be a bool, or it will not compile:
error[E0308]: mismatched types --> src/main.rs:3:8 | 3 | if message_count { | ^^^^^^^^^^^^^ expected `bool`, found integer
It is the E0308 you learned to read in lesson 1.5, "mismatched types": the compiler expected a bool and found a number. The fix is to ask a real question, such as message_count > 0. Comparisons like >, < and == always give back a bool, and so does ! in front of one, which means "not": !quiet is true exactly when quiet is false.
if is an expression
In lesson 1.6 you met the difference between a statement, a step that does its work and produces nothing, and an expression, a piece of code that produces a value. In Rust, if is an expression. Whichever block runs, its last line (with no semicolon) becomes the value of the whole if.
What does this print?
chattyquiettrue
Reveal the answer
The program prints: chatty 7 is greater than 5, so the first block is chosen, and its last line, "chatty", becomes the value that label holds. The comparison itself is true, but that only picks the road; it is not what comes out. Both blocks must give the same kind of value, because label can only be one kind.
More than two roads: else if
Writing else if adds one more question that is only asked when every question above it said no. Rust walks down the chain from the top and runs the first block whose question is true, or the final else if none is. Exactly one block runs, so the whole chain is still a single expression with a single value.
That is exactly what a function body wants. A function hands back the value of its last expression (lesson 1.6), so a function whose body is one if / else if / else chain returns whatever the chosen block produces. No early exits, no temporary names: the chain is the answer.
If you have coded before
Same idea, different punctuation: braces instead of a colon and indentation, else if instead of elif, and no brackets around the condition. Python lets if items: treat an empty list as false. Rust asks you to say the question out loud, items.is_empty(), every time. And Rust's if doubles as Python's x if cond else y.
Chatterbox v0.3: reply() is born
Here is the whole program after this lesson. The green lines are new, and they make two kinds of choice.
The quiet switch finally does something. The greeting is printed only if !quiet. Set quiet to true and the greeting disappears. The line that printed the settings is gone: they now change what Chatterbox does, so there is no need to show them.
A new function, reply(message: &str) -> String, decides what the bot says back. Its body is one chain of questions, asked in this order:
- Is the message longer than
MAX_LEN, the constant from lesson 2.6? (len()counts bytes, lesson 2.5.) Then it says the message is too long, and names the limit. - Does it end with a question mark?
ends_with('?')answers exactly that (a single character goes in single quotes). Questions get a playful answer of their own: Good question! I can only echo for now. - Otherwise it echoes the message back:
you said: ….
Order matters: a very long question is caught by the length check first and never reaches the question-mark check. Each block's last line builds a String, so whichever road is taken, that String is what reply returns.
In main, an empty message is not worth answering, so if message.is_empty() gets an empty block on purpose, and only the else block counts the message and prints the reply. That changes what the counter means. Until now it went up once on every run, standing in for a message that did not exist yet. From now on it counts only messages sent to the bot: never the greeting, never an empty line, and, once the keyboard is plugged in, only what you type. Every answer now starts with bot:, so you can always tell who is talking.
The message itself is written into the program for now ("are you awake?"), so the run under the code answers that question. The last lesson of this chapter plugs the keyboard in.
Chatterbox v0.3 Hi Sam! I'm Chatterbox. Ask me anything. bot: Good question! I can only echo for now. Ask me again in chapter 9. messages so far: 1
Show the whole program (open it after you have tried the exercise below: it contains the answer)
Download this version (zip)Unzip, then cargo run inside the folder.
This is Chatterbox v0.3 with the body of reply replaced by todo!(), which stops the program with a "not yet written" message. Write the chain: a message longer than MAX_LEN bytes gets that is too long (the limit is 200 bytes), a message ending in ? gets the Good question answer exactly as before, and anything else gets you said: followed by the message. A message of exactly 200 bytes is allowed.
This is Chatterbox v0.3 with the body of reply replaced by todo!(), which stops the program with a "not yet written" message. Write the chain: a message longer than MAX_LEN bytes gets that is too long (the limit is 200 bytes), a message ending in ? gets the Good question answer exactly as before, and anything else gets you said: followed by the message. A message of exactly 200 bytes is allowed.
Hidden tests (5): a_question_gets_its_own_answer a_message_is_echoed a_long_question_is_still_too_long exactly_the_limit_is_allowed too_long_names_the_limit
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
Say it out loud, then reveal
What kind of value must an if condition be?Reveal
bool: true or false. Rust will not turn numbers or text into one for you.Can both the if block and the else block run?Reveal
In an if / else if chain, which block runs?Reveal
else runs (or nothing, when there is no else).Why can the whole body of reply be one if / else if / else chain?Reveal
if is an expression: the chosen block's last line is its value, and a function returns the value of its last expression.That is lesson 3.1. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
How do I write an if statement in Rust?
Write if, then a question that is true or false, then the code to run in curly braces. Add else and another pair of braces for what to do when the answer is false, and else if for more questions in between.
Why does Rust not allow if with a number?
Rust only accepts a true or false value as a condition, so you have to ask a real question such as count > 0. That stops a whole class of mistakes where a value is treated as true or false by accident.
Can if return a value in Rust?
Yes. if is an expression: the last line of whichever block runs becomes its value, so you can write let label = if big { "chatty" } else { "quiet" };. Both blocks must give the same type.
How do I check if a string is empty in Rust?
Call is_empty() on it. It answers true when the text has nothing in it and false otherwise.
Sources The Rust Book: control flow
