Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Learn RustChapter 3: Decisions

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 (a group of values, such as a list) one item at a time and stops by itself at the end.

Start with while, which reads like English:

while: keep going while the question is true
fn main() {
let mut retries = 3;
while retries > 0 {
println!("retries left: {retries}");
retries -= 1;
}
println!("giving up");
}
$ cargo run
retries left: 3
retries left: 2
retries left: 1
giving up

The 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:

loop: forever, until break
fn main() {
let mut turns = 0;
loop {
turns += 1;
if turns == 4 {
break;
}
}
println!("stopped after {turns} turns");
}
$ cargo run
stopped after 4 turns

for: 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 (Rust calls this an array), 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.)

PredictWhere does it stop?
fn main() {
let messages = ["hi", "/quit", "hello"];
for message in messages {
if message == "/quit" {
break;
}
println!("{message}");
}
}

What does this print?

  • hi
  • hi /quit hello
  • hello
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.

break has a smaller sibling, continue. Where break leaves the whole loop, continue skips only the rest of this turn and jumps straight to the next item. It is the tool for "ignore this one and carry on", such as an empty message:

continue: skip this item, keep looping
fn main() {
let messages = ["hi", "", "hello"];
for message in messages {
if message.is_empty() {
continue;
}
println!("you: {message}");
}
}
$ cargo run
you: hi
you: hello

The empty message never reaches the println!, but unlike break, the loop goes on and hello is still printed. Both words work the same way inside loop and while too.

If you have coded before

for message in messages:, break and continue mean the same thing. while too. The one difference is loop, which Python writes as while True:.

Chatterbox v0.3: the chat loop

A chat is many messages, so the single written-in message becomes a pretend conversation: an array of six. The match from last lesson moves, unchanged, inside a for, so every message gets the same treatment, and reply and HELP do not change at all. The keyboard is still missing (it arrives at the end of this chapter), but Chatterbox now works through this list exactly the way it will soon work through yours.

The one new idea inside the loop is in the /quit arm. It still says goodbye, and then break leaves the loop, so /quit finally means "leave". Follow the list through the run under the code:

  • "hello" is echoed and counted.
  • "" is skipped without a word.
  • "/help" lists the commands.
  • "are you awake?" gets the question answer and is counted.
  • "/quit" says goodbye and breaks out.
  • "never answered" is never looked at, which is why it is called that.

So the count at the end is 2. This version reads its own list instead of the keyboard.

Chatterbox v0.3 after lesson 3.3: the whole program (green lines are new in this lesson)
src/main.rs21 new lines
// Chatterbox: a small chat program, built one lesson at a time.
 
/// What the bot is called. A constant: fixed for the whole program.
const BOT: &str = "Chatterbox";
/// The version as a pair of numbers: (major, minor).
const VERSION: (u32, u32) = (0, 3);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /quit";
 
/// The first line Chatterbox prints.
fn banner() -> String {
format!("{} v{}.{}", BOT, VERSION.0, VERSION.1)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str) -> String {
let mut text = format!("Hi {}! I'm {}.", name, BOT);
text.push_str(" Ask me anything.");
text
}
 
/// What the bot says back to one message.
fn reply(message: &str) -> String {
if message.len() > MAX_LEN {
format!("that is too long (the limit is {} bytes)", MAX_LEN)
} else if message.ends_with('?') {
String::from("Good question! I can only echo for now. Ask me again in chapter 9.")
} else {
format!("you said: {}", message)
}
}
 
fn main() {
let name = "Sam";
let mut messages_seen: u32 = 0;
let quiet = false; // true skips the greeting
 
println!("{}", banner());
if !quiet {
println!("{}", greeting(name));
}
 
// A pretend conversation. The next lesson swaps it for what you type.
let messages = [
"hello",
"",
"/help",
"are you awake?",
"/quit",
"never answered",
];
 
for message in messages {
match message {
"" => {} // nothing typed: nothing to answer
"/help" => println!("bot: {}", HELP),
"/quit" => {
println!("bot: bye, {}!", name);
break;
}
other => {
messages_seen += 1;
println!("bot: {}", reply(other));
}
}
}
println!("messages so far: {}", messages_seen);
}
Chatterbox prints (a real run)
Chatterbox v0.3
Hi Sam! I'm Chatterbox. Ask me anything.
bot: you said: hello
bot: commands: /help, /quit
bot: Good question! I can only echo for now. Ask me again in chapter 9.
bot: bye, Sam!
messages so far: 2

Download this version (zip)Unzip, then cargo run inside the folder.

Try itYour turn: how many before /quit?

A small warm-up, separate from Chatterbox. 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. The type [&str; 4] means an array of exactly 4 pieces of text.

A small warm-up, separate from Chatterbox. 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. The type [&str; 4] means an array of exactly 4 pieces of text.

fn count_before_quit(messages: [&str; 4]) -> u32 {
let mut count = 0;
// walk the messages; stop at "/quit"
count
}
 
fn main() {
println!("{}", count_before_quit(["a", "b", "/quit", "c"]));
}

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.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
Which loop repeats until you call break?Reveal
loop.
When is for a better choice than while?Reveal
When you have a collection and want to visit each item once. It stops by itself at the end.
What does break do inside a for loop?Reveal
It leaves the loop at once. The rest of the items are never visited.
What is the difference between break and continue?Reveal
break leaves the whole loop. continue skips only the rest of the current turn and goes on with the next item.

That is lesson 3.3. Tick it off so the course remembers where you are.

Next: 3.4 Reading a line →

Questions people ask

What are the three kinds of loop in Rust?

loop repeats until you break out of it, while repeats as long as a condition stays true, and for visits each item of a collection once and then stops.

How do I stop a loop early in Rust?

Write break. The loop ends at once and the program carries on with the line after it. To skip just one turn and keep looping, write continue instead.

What is an array in Rust?

An array is a list with a fixed number of items, all of the same type, written in square brackets such as ["hi", "bye"]. Lists that can grow are called Vec.

Why does my while loop never end?

Nothing inside it ever makes the condition false. Make sure the loop changes the value it is checking, for example by counting down.

Learn Rust by building a chat app · Lesson 3.3 · every compiler message above is real output from rustc 1.99.0 (b940084d7 2026-09-28) (edition 2024) · Vibe Engines · 2026