Lesson 3.3 · 10 min
Doing things again
A chat is not one message, it is a stream of them. To handle the next message the same way as the last one you do not copy the code, you tell Rust to repeat it. Rust has three loops, and you will use all three.
Adds to ChatterboxThe chat loop.
Three loops
loop repeats forever, until you say break. while repeats as long as a question stays true. for goes through a collection one item at a time and stops by itself at the end.
Start with while, which reads like English:
$ cargo run
retries left: 3
retries left: 2
retries left: 1
giving upThe value changes inside the loop (retries -= 1, which is why it is let mut from lesson 2.2). If nothing ever made the question false the loop would never end, so check that something does.
Now loop with break. It is the right tool when the exit is in the middle of the work:
$ cargo run
stopped after 4 turnsfor: one item at a time
Most of the time you have a list and want to do something to each item. That is for. A list of fixed size is written in square brackets, and for x in list gives each item the name x in turn. (Lists that grow are chapter 6; this fixed one is all we need now.)
What does this print?
hihi /quit hellohello
Reveal the answer
The program prints: hi The loop prints hi, then sees /quit and leaves the whole loop with break. The third item is never looked at.
Chatterbox v0.3, the chat loop
There is no keyboard yet (two lessons from now), so Chatterbox works through a canned list of messages the way it will soon work through yours. The match from last lesson moves inside a for, and /quit now does what it says: it prints a goodbye and leaves the loop. Everything after /quit is never read.
$ cargo run
Chatterbox v0.3
Hi Sam! I'm Chatterbox.
you: hello
(nothing to say)
commands: /help, /quit
you: how are you
bye, Sam!
messages so far: 2Finish count_before_quit. It receives four messages and returns how many come before the first /quit. If there is no /quit, that is all four. You don't need to understand fn yet (chapter 3, lesson 4 explains it): just fill in the body. The type [&str; 4] means an array of exactly 4 pieces of fixed text.
Finish count_before_quit. It receives four messages and returns how many come before the first /quit. If there is no /quit, that is all four. You don't need to understand fn yet (chapter 3, lesson 4 explains it): just fill in the body. The type [&str; 4] means an array of exactly 4 pieces of fixed text.
Hidden tests (3): no_quit_counts_all quit_first_counts_none stops_at_quit
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
Say it out loud, then reveal
Which loop repeats until you call break?Reveal
loop.When is for a better choice than while?Reveal
What does break do inside a for loop?Reveal
That is lesson 3.3. Tick it off so the course remembers where you are.