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.
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.
$ cargo run
sam: hi
1 messagesNumbering 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.
What does this program print?
1080
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:ifor the position andmfor the message.- The line prints
i + 1, a dot, andm.to_line(), so you see1. 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.
Sam hello /count /quit
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.
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.
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.
Say it out loud, then reveal
What is the difference between for m in history and for m in &history?Reveal
What does enumerate give you at each step?Reveal
Why does a running total have to be made before the loop?Reveal
That is lesson 6.2. Tick it off so the course remembers where you are.
Go deeper
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.