Lesson 6.1 · 8 min
A list: Vec
So far Chatterbox forgets every message the moment it handles it. To keep a conversation you need a list that grows. Rust's growable list is called Vec, and it follows the same one-owner rule you already know.
Adds to ChatterboxThe history becomes a Vec of messages.
A list that grows
A Vec (said "vec", short for vector) is a list of values that all have the same type, and it can grow. You write the type as Vec<Message>: a Vec of Messages. The part in angle brackets says what is inside.
Think of it with the one-owner rule from chapter 4, which applies here exactly as before: the Vec owns every item in it. When the Vec goes away, its items go with it. Nobody else holds a copy.
$ cargo run
2 people
first is samVec::new() makes an empty list. When you already know the items, vec!["sam".to_string(), "ada".to_string()] makes a list with them in it: vec! is a macro (like println!) that builds a Vec from the items you list. push adds one item at the end, so the Vec has to be mut (you met mut in chapter 2). len() says how many items it holds. (Its answer, and any position you pass, has the type usize: a number that means "a position or a size".) names[0] reads the item at position 0: counting starts at zero, so the first item is number 0. In the next program, .clone() makes a second, separate copy of a String, so the function can hand one back while the list keeps its own. And its parameter is written &[String]: a borrowed view of a list of Strings, the way &str is a borrowed view of text (lesson 4.6). Passing &names lends the Vec as exactly that view.
What if the position is not there?
There are only two names in that list. What happens if you ask for position 5?
This program asks for position 5 of a two-item list. What happens?
- It compiles and runs
- It compiles, then panics
- Compile error E0308
Reveal the answer
It compiles, then panics at run time. The program compiles, because the compiler cannot know how long the list is at run time. When it runs, position 5 does not exist, so the program stops with a panic: "index out of bounds". Reading by [ ] is a promise that the item is there. If you break the promise, the program crashes.
The polite way: get
A chat program receives messages from other people, so "position 5 does not exist" is a normal thing to meet, not a bug. For those cases a Vec has get. It does not crash. It returns an Option (lesson 5.4): Some(item) when the position exists and None when it does not.
Use [ ] when you have just checked the length or the position is certain. Use get whenever it might be missing.
$ cargo run
Some("ada")
NoneChatterbox v0.6: the history is a list
Until now Chatterbox kept the conversation in one long String, the transcript that record added lines to. That was enough for printing, but a String has forgotten where one message ends and the next begins. Now the history is a Vec<Message>: every message kept whole, in the order it was said. Here is the whole program after this lesson, new lines in green.
let mut history: Vec<Message> = Vec::new();takes the place of the transcript. It starts empty and ismutbecause it will grow.- After each message,
history.push(said)andhistory.push(answer)hand both messages to the Vec. From then on the Vec owns them. recordis gone. Nothing needs to glue text into a String any more./historyaskshistory.is_empty()first, then prints each message'sto_line()withfor m in &history. The&means the loop only borrows the messages, so the history is still there afterwards. Walking a list like this is the whole of the next lesson.
Type a couple of messages and /history, and the output looks exactly as it did in chapter 5. What changed is underneath: the program now holds real messages it can count, number and search, which is what the rest of this chapter does.
Sam hello how are you? /history /quit
Chatterbox v0.6 What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. bot: you said: hello bot: Good question! I can only echo for now. Ask me again in chapter 9. you: hello bot: you said: hello you: how are you? 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.
Two owners need two copies
One new line has a comment above it, and it is worth reading slowly: last = Some(text);.
Remember lesson 4.3: a value has exactly one owner, and handing it over moves it. The text you just typed is now wanted in two places. last keeps it so /again can repeat it, and the history keeps the whole message, text included. One String cannot belong to both, so two owners need two Strings. The question is where the second one comes from.
It was made a few lines earlier, by Message::new("you", &text). The & only lends text, and new builds the message's own String from that loan (lesson 5.2). So the message that moves into the history already owns its copy. The original text, which came out of the Chat command, is still whole, and nothing else needs it any more, so it moves into last. Two owners, two Strings, and no extra copying: the comment says so, so the next reader does not go looking for one.
The chapter 5 line, last = Some(said.text);, would no longer work. It moved the text out of said, and now said itself moves into the Vec. A message whose text has been moved out cannot be pushed whole, and the compiler refuses with the same E0382 "moved value" error you met in lesson 4.3:
error[E0382]: use of partially moved value: `said` --> src/main.rs:10:18 | 9 | let last = Some(said.text); | --------- value partially moved here 10 | history.push(said); | ^^^^ value used here after partial move | = note: partial move occurs because `said.text` has type `String`, which does not implement the `Copy` trait
Write last_text. It returns Some(text) of the newest message (the one at the end of the Vec), or None if the history is empty. It must never crash. It takes &[Message], a borrowed view of the list, so it can read the history without owning it.
Write last_text. It returns Some(text) of the newest message (the one at the end of the Vec), or None if the history is empty. It must never crash. It takes &[Message], a borrowed view of the list, so it can read the history without owning it.
Hidden tests (3): empty_history_has_no_last_text newest_is_the_last_one_pushed single_message
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
What you have now
Chatterbox keeps a Vec<Message>. You can push, count, index and get. The list owns its messages, and a missing position is something you handle, not something you hope never happens. Next you will walk through the list instead of picking one position at a time.
Say it out loud, then reveal
What is the difference between names[5] and names.get(5) on a two-item Vec?Reveal
Why does the Vec need to be mut before you push?Reveal
Who owns the Messages you push?Reveal
That is lesson 6.1. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
What does Vec stand for in Rust?
Vec is short for vector: a growable list of values that all have the same type.
Is a Rust Vec the same as a Python list?
It is the closest match, but every item must be the same type, and reading past the end panics instead of raising an exception you can catch in the usual way.
How do I make a Vec with items already in it?
Use the vec! macro, for example vec![1, 2, 3].
