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.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.

Make a list, add to it, count it
fn main() {
let mut names: Vec<String> = Vec::new();
names.push("sam".to_string());
names.push("ada".to_string());
println!("{} people", names.len());
println!("first is {}", names[0]);
}
$ cargo run
2 people
first is sam

Vec::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?

PredictPast the end
fn pick(names: &[String], i: usize) -> String {
names[i].clone()
}
 
fn main() {
let names = vec!["sam".to_string(), "ada".to_string()];
println!("{}", pick(&names, 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.

get hands back an Option
fn main() {
let names = vec!["sam".to_string(), "ada".to_string()];
println!("{:?}", names.get(1));
println!("{:?}", names.get(5));
}
$ cargo run
Some("ada")
None

Chatterbox 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 is mut because it will grow.
  • After each message, history.push(said) and history.push(answer) hand both messages to the Vec. From then on the Vec owns them.
  • record is gone. Nothing needs to glue text into a String any more.
  • /history asks history.is_empty() first, then prints each message's to_line() with for 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.

Chatterbox v0.6 after lesson 6.1: the whole program (green lines are new in this lesson)
src/main.rs11 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, /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,
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,
"/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 m in &history {
println!("{}", m.to_line());
}
}
}
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);
}
Cargo.toml1 new line
[package]
name = "chatterbox"
version = "0.6.0"
edition = "2024"
 
[dependencies]
You type
Sam
hello
how are you?
/history
/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: 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:

The chapter 5 line, kept: the text moved out, so the whole message cannot move in
struct Message {
author: String,
text: String,
}
 
fn main() {
let mut history: Vec<Message> = Vec::new();
let said = Message { author: String::from("you"), text: String::from("hello") };
let last = Some(said.text);
history.push(said);
println!("{} messages, last: {:?}", history.len(), last);
}
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
Try itYour turn: the last thing said

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.

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 last_text(history: &[Message]) -> Option<String> {
// newest message = the last position in the list
None
}
 
fn main() {
let mut history: Vec<Message> = Vec::new();
println!("{:?}", last_text(&history));
history.push(Message::new("sam", "hello"));
println!("{:?}", last_text(&history));
}

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.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What is the difference between names[5] and names.get(5) on a two-item Vec?Reveal
names[5] panics (the program crashes). names.get(5) returns None, so you can handle it.
Why does the Vec need to be mut before you push?Reveal
push changes the list, and Rust makes you say a value may change by writing mut.
Who owns the Messages you push?Reveal
The Vec. After the push the message has moved in, and the Vec drops it when the Vec itself goes away.

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

Next: 6.2 Walking a list →

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].

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