Vibe Engines
YouTube

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

Learn RustChapter 6: Collections

Lesson 6.2 · 9 min

Walking a list

A history is only useful if you can look through it: print every message, number them, add up their lengths. Walking a list is also where the one-owner rule shows up again, because a loop can either borrow the items or take them.

Adds to ChatterboxNumbered /history, and /count.

Loop and keep the list

In lesson 6.1, /history printed the list with for m in &history. Why the &? It answers a question that matters every time you loop over a Vec: after the loop, do you still have the list?

That depends on what you hand to for. If you give it the Vec itself, the loop takes the Vec: it becomes the owner and hands you the items one at a time. If you give it &history (a borrow, from chapter 4), the loop only looks at the items, and the Vec stays yours.

The loop took the list, so it is gone
struct Message {
author: String,
text: String,
}
 
fn main() {
let history = vec![Message { author: "sam".to_string(), text: "hi".to_string() }];
for m in history {
println!("{}: {}", m.author, m.text);
}
println!("{} messages", history.len());
}
error[E0382]: borrow of moved value: `history`
  --> src/main.rs:11:29
   |
 7 |     let history = vec![Message { author: "sam".to_string(), text: "hi".to_string() }];
   |         ------- move occurs because `history` has type `Vec<Message>`, which does not implement the `Copy` trait
 8 |     for m in history {
   |              ------- `history` moved due to this implicit call to `.into_iter()`
...
11 |     println!("{} messages", history.len());
   |                             ^^^^^^^ value borrowed here after move
   |
note: the `for` loop is desugared into a call to `std::iter::IntoIterator::into_iter`, which takes ownership of the receiver `self`, which moves `history`
  --> /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/core/src/iter/traits/collect.rs:312:17
help: consider iterating over a slice of the `Vec<Message>`'s content to avoid moving into the `for` loop
   |
 8 |     for m in &history {
   |              +

The compiler says "borrow of moved value: history". Read it as: you gave history to the loop, so it is not yours any more, and then you asked it for its length. The fix is one character. Write for m in &history and the loop borrows instead.

Borrow it with &, and the list survives
struct Message {
author: String,
text: String,
}
 
fn main() {
let history = vec![Message { author: "sam".to_string(), text: "hi".to_string() }];
for m in &history {
println!("{}: {}", m.author, m.text);
}
println!("{} messages", history.len());
}
$ cargo run
sam: hi
1 messages

Numbering with enumerate

A loop often needs to know where it is as well as what it is looking at: "this is message 3". history.iter() is the same borrowing walk as &history, written as a method: it lends you one item at a time. Add .enumerate() after it and each step hands you two things instead of one, the position and the item, which you unpack into two names with (i, m).

Positions start at 0, because a position counts how many items come before this one: the first message has nothing before it. People count from 1, so a numbered list prints i + 1.

A running total

The other common walk adds something up. Make a number before the loop, starting at 0, and add to it once per item. The number lives outside the loop, so it survives every turn and holds the answer when the loop ends. Each m is only borrowed for one turn, but what you add to the total is a plain number, copied out, so nothing is left pointing into the list.

PredictCount from where?
fn main() {
let history = vec!["hi".to_string(), "hello".to_string(), "hey".to_string()];
let mut total = 0;
for (i, text) in history.iter().enumerate() {
if i == 0 {
continue;
}
total += text.len();
}
println!("{total}");
}

What does this program print?

  • 10
  • 8
  • 0
Reveal the answer

The program prints: 8 Position 0 is the first item, "hi", and continue (lesson 3.3) skips the rest of that turn and moves on to the next item. The loop then adds "hello" (5 bytes) and "hey" (3 bytes), so the total is 8. If you expected 10, you were counting positions from 1, so i == 0 looked as if it could never happen; but the first item is at position 0, so it is the one skipped. If you expected 0, you read continue as break: break leaves the whole loop, continue skips only one turn.

Chatterbox v0.6: numbered /history, and /count

Here is the whole program after this lesson, new lines in green. Two things changed, and both are walks over the history that borrow it.

/history now numbers its lines. The loop reads for (i, m) in history.iter().enumerate(). Take it one piece at a time:

  • history.iter() walks the list and lends you one message at a time, the same borrowing walk as &history.
  • .enumerate() pairs each message with its position: first (0, the first message), then (1, the second), and so on.
  • (i, m) unpacks each pair into two names: i for the position and m for the message.
  • The line prints i + 1, a dot, and m.to_line(), so you see 1. you: hello. Positions start at 0, people count from 1.

/count is a new command (it is in the help text, it has its own Command::Count variant, and parse knows the word). It walks the history with for m in &history, adds up m.text.len() for every message, and reports how many messages there are and how many bytes of text they hold. It says "bytes" on purpose: len() counts bytes, not characters (lesson 2.5). The count includes the bot's replies, because they are in the history too, so one "hello" makes two messages.

That is the running total from above, and it only borrows: after /count, the history is all still there for the next /history. The end of this chapter shows a way to write a walk like this in one line; the plain loop is how it works underneath.

Chatterbox v0.6 after lesson 6.2: the whole program (green lines are new in this lesson)
src/main.rs12 new lines
// Chatterbox: a small chat program, built one lesson at a time.
use std::io;
 
/// 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, 6);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /count, /say <text>, /shout <text>, /debug <text>, /quit (or /h, /q, /exit)";
 
/// One line of the conversation: who said it, and what they said.
struct Message {
author: String,
text: String,
}
 
impl Message {
/// Make a Message from two pieces of borrowed text.
fn new(author: &str, text: &str) -> Message {
Message {
author: String::from(author),
text: String::from(text),
}
}
 
/// The message as one transcript line: "you: hello".
fn to_line(&self) -> String {
format!("{}: {}", self.author, self.text)
}
 
/// The text in capitals, for /shout.
fn shout(&self) -> String {
self.text.to_uppercase()
}
}
 
/// Everything a line of input can mean. One enum, so a `match` on it must
/// handle every kind of line: the compiler checks that nothing is forgotten.
#[derive(Debug)]
enum Command {
Empty,
Help,
Quit,
Again,
History,
Count,
Say(Option<String>),
Shout(Option<String>),
Unknown(String),
Debug(Option<String>),
Chat(String),
}
 
/// A borrowed Option<&str> turned into an owned Option<String>, so the
/// Command can keep the text after `line` is gone.
fn owned(text: Option<&str>) -> Option<String> {
match text {
Some(t) => Some(String::from(t)),
None => None,
}
}
 
/// Turn one line of input into a Command.
fn parse(line: &str) -> Command {
match first_word(line) {
"" => Command::Empty,
"/help" | "/h" => Command::Help,
"/quit" | "/q" | "/exit" => Command::Quit,
"/again" => Command::Again,
"/history" => Command::History,
"/count" => Command::Count,
"/debug" => Command::Debug(owned(arg(line))),
"/say" => Command::Say(owned(arg(line))),
"/shout" => Command::Shout(owned(arg(line))),
word => {
if is_command(word) {
Command::Unknown(String::from(word))
} else {
Command::Chat(String::from(line))
}
}
}
}
 
/// 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
}
 
/// True when the text is a command: it starts with a slash.
fn is_command(text: &str) -> bool {
text.starts_with('/')
}
 
/// The first word of the text: a slice (&str) pointing into it, not a copy.
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[..i],
None => text,
}
}
 
/// The text after the command word, if there is any: Some("hello") for
/// "/say hello", None for a bare "/say". No more "" standing in for nothing.
fn arg(line: &str) -> Option<&str> {
match line.find(' ') {
Some(i) => {
let rest = line[i + 1..].trim();
if rest.is_empty() { None } else { Some(rest) }
}
None => None,
}
}
 
/// What the bot says back to an ordinary message (not a command).
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 mut messages_seen: u32 = 0;
let quiet = false;
let mut last: Option<String> = None; // the last thing you said, for /again
let mut history: Vec<Message> = Vec::new(); // everything said so far, in order
 
println!("{}", banner());
println!("What should I call you?");
let mut name_line = String::new();
io::stdin().read_line(&mut name_line).unwrap();
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line).unwrap();
if bytes == 0 {
break; // no more input: the keyboard was closed
}
let message = line.trim();
match parse(message) {
Command::Empty => {} // nothing typed: nothing to answer
Command::Quit => {
println!("bot: bye, {}!", name);
break;
}
Command::Help => println!("bot: {}", HELP),
Command::Again => {
if let Some(text) = &last {
println!("bot: {}", reply(text));
} else {
println!("bot: nothing to repeat yet");
}
}
Command::History => {
if history.is_empty() {
println!("bot: nothing said yet");
} else {
for (i, m) in history.iter().enumerate() {
println!("{}. {}", i + 1, m.to_line());
}
}
}
Command::Count => {
let mut bytes = 0;
for m in &history {
bytes += m.text.len();
}
println!("bot: {} messages, {} bytes of text", history.len(), bytes);
}
Command::Say(Some(text)) => println!("bot: {}", text),
Command::Say(None) => println!("bot: say what? Try /say hello"),
Command::Shout(Some(text)) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Shout(None) => println!("bot: shout what? Try /shout hello"),
Command::Unknown(word) => {
println!("bot: I don't know the command {}. Try /help.", word)
}
Command::Debug(Some(text)) => println!("bot: {:?}", parse(&text)),
Command::Debug(None) => println!("bot: debug what? Try /debug /say hi"),
Command::Chat(text) => {
messages_seen += 1;
let said = Message::new("you", &text);
let answer = Message::new("bot", &reply(&said.text));
println!("bot: {}", answer.text);
history.push(said);
history.push(answer);
// Message::new made the history its own copy, so `text` itself can
// be handed to `last` for /again: no extra copy needed.
last = Some(text);
}
}
}
println!("messages so far: {}", messages_seen);
}
You type
Sam
hello
/count
/quit
Chatterbox prints (a real run)
Chatterbox v0.6
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: you said: hello
bot: 2 messages, 20 bytes of text
bot: bye, Sam!
messages so far: 1

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

Try itYour turn: the numbered list

Write numbered. For each message return one line in the form 1. sam: hello: the position starting at 1, the author, a colon and a space, then the text. Like last_text in lesson 6.1, it takes &[Message], a borrowed view of the list.

Write numbered. For each message return one line in the form 1. sam: hello: the position starting at 1, the author, a colon and a space, then the text. Like last_text in lesson 6.1, it takes &[Message], a borrowed view of the list.

struct Message {
author: String,
text: String,
}
 
impl Message {
fn new(author: &str, text: &str) -> Message {
Message { author: author.to_string(), text: text.to_string() }
}
}
 
fn numbered(history: &[Message]) -> Vec<String> {
// one String per message: "1. sam: hello"
Vec::new()
}
 
fn main() {
let history = vec![Message::new("sam", "hello"), Message::new("ada", "hi")];
for line in numbered(&history) {
println!("{line}");
}
}

Hidden tests (4): empty_history_gives_no_lines numbers_follow_the_order history_is_still_usable_after one_message

This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.

What you have now

You can walk a history without losing it: for m in &history borrows, for m in history takes. You can number items with enumerate, and keep a running total that outlives the loop. Next: a different kind of container, for looking things up by name rather than by position, so Chatterbox can /remember and /recall.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What is the difference between for m in history and for m in &history?Reveal
The first moves the Vec into the loop, so you cannot use it afterwards. The second borrows it, so the Vec is still yours when the loop ends.
What does enumerate give you at each step?Reveal
A pair: the position (starting at 0) and the item.
Why does a running total have to be made before the loop?Reveal
A name made inside the loop body is made fresh on every turn and gone at the end of it. The total must survive every turn, so it lives outside the loop.

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

Questions people ask

What is E0382 in Rust?

Use of a moved value. You gave a value away (here, to a for loop) and then tried to use it again.

Should I write for m in &history or for m in history.iter()?

They do the same thing. Both borrow the items. The &history form is shorter and most common.

Why does enumerate start counting at 0?

A position in Rust counts how many items come before this one, so the first item is at 0. That is also the number you would use with square brackets, as in history[0]. Add one when you print a list for people.

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