Vibe Engines
YouTube

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

Learn RustChapter 5: Shapes

Lesson 5.1 · 7 min

Bundling fields: struct

Chatterbox keeps passing around an author in one string and the text in another, and hoping they stay together. A struct gives them one name and one owner.

Adds to ChatterboxA Message struct.

Two strings that belong together

Chatterbox v0.4 records every line into a transcript. But a line has two facts: who said it, and what they said. Today those travel as two loose strings, and nothing stops you from handing the bot's text to the wrong author.

A struct is a named bundle of fields (named slots, each holding one value). You decide the fields once, and from then on a Message is one thing you can pass around, store and borrow.

Define the shape once, then build values of it
struct Message {
author: String,
text: String,
}
 
fn main() {
let m = Message {
author: String::from("you"),
text: String::from("hello"),
};
println!("{}: {}", m.author, m.text);
}
$ cargo run
you: hello

The first four lines describe the shape: a Message has an author and a text, both String (lesson 2.5). Inside main we build one by naming every field. Then m.author and m.text read a field with a dot.

Every field must be given. Leave one out and the compiler stops you, which is the point: a Message with no author cannot exist.

A field left out
struct Message {
author: String,
text: String,
}
 
fn main() {
let m = Message {
author: String::from("you"),
};
println!("{}", m.author);
}
error[E0063]: missing field `text` in initializer of `Message`
 --> src/main.rs:7:13
  |
7 |     let m = Message {
  |             ^^^^^^^ missing `text`

E0063 says "missing field text". Not a warning, not a default of empty: the program does not build until the shape is complete.

A struct owns its fields

Remember the one-key model from chapter 4. Each String has exactly one owner. Inside a Message, the message owns its author and its text. When the message goes away, its fields go with it. Move the message and you move everything inside it in one go.

That is why the new record in Chatterbox takes &Message: it only needs to look, so it borrows. The caller keeps the key.

PredictRead the fields
struct Message {
author: String,
text: String,
}
 
fn main() {
let m = Message {
text: String::from("ping"),
author: String::from("bot"),
};
println!("{}: {}", m.author, m.text);
}

What does this print?

  • bot: ping
  • ping: bot
  • it does not compile
Reveal the answer

The program prints: bot: ping Fields are matched by name, not by position. Writing text first does not swap them. That is a quiet gift of structs: you cannot mix up two strings of the same type.

Chatterbox v0.5: every line is a Message

Here is the whole program after this lesson. The green lines are the change; everything else is exactly what you had at the end of chapter 4.

  • At the top, the Message struct: an author and a text, both owned Strings.
  • record used to take two loose strings, who and text. Now it takes one borrowed &Message and reads msg.author and msg.text with a dot. The & in push_str(&msg.author) lends the field to push_str, which only needs to read it; the message keeps its own text. It still gets &mut on the transcript, because it adds to it (lesson 4.5).
  • In the loop, what you typed becomes said, a Message from you, and the bot's answer becomes answer, a Message from bot. Both are recorded, and answer.text is printed.

Type /history and the transcript comes out exactly as before. That is the point of this change: nothing you can see is different, but the author and the text can no longer be handed to record in the wrong order.

Chatterbox v0.5 after lesson 5.1: the whole program (green lines are new in this lesson)
You type
Sam
hello
how are you?
/history
/quit
Chatterbox prints (a real run)
Chatterbox v0.5
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
Show the whole program (open it after you have tried the exercise below: it contains the answer)
src/main.rs25 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, 5);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /say <text>, /quit";
 
/// One line of the conversation: who said it, and what they said.
struct Message {
author: String,
text: String,
}
 
/// Add one message to the transcript.
fn record(log: &mut String, msg: &Message) {
log.push_str(&msg.author);
log.push_str(": ");
log.push_str(&msg.text);
log.push('\n');
}
 
/// 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.
/// It only looks at the text, so it borrows it (&str) and never owns it.
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,
}
}
 
/// Everything after the first space, or "" when there is no space.
fn rest_of(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[i + 1..],
None => "",
}
}
 
/// 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 mut messages_seen: u32 = 0;
let quiet = false; // true skips the greeting
let mut last = String::new(); // the last thing you said, for /again
let mut transcript = String::new(); // everything said so far
 
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 first_word(message) {
"" => {} // nothing typed: nothing to answer
"/help" => println!("bot: {}", HELP),
"/quit" => {
println!("bot: bye, {}!", name);
break;
}
"/again" => {
if last.is_empty() {
println!("bot: nothing to repeat yet");
} else {
println!("bot: {}", reply(&last));
}
}
"/history" => {
if transcript.is_empty() {
println!("bot: nothing said yet");
} else {
print!("{}", transcript);
}
}
"/say" => println!("bot: {}", rest_of(message)),
_ => {
if is_command(message) {
println!(
"bot: I don't know the command {}. Try /help.",
first_word(message)
);
} else {
messages_seen += 1;
let said = Message {
author: String::from("you"),
text: String::from(message),
};
let answer = Message {
author: String::from("bot"),
text: reply(&said.text),
};
record(&mut transcript, &said);
record(&mut transcript, &answer);
println!("bot: {}", answer.text);
last = said.text; // the text moves out of `said`, which is not used again
}
}
}
}
println!("messages so far: {}", messages_seen);
}
Cargo.toml1 new line
[package]
name = "chatterbox"
version = "0.5.0"
edition = "2024"
 
[dependencies]

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

One line deserves a closer look: last = said.text;. You can move a single field out of a struct. The text String is handed over to last (for /again, from lesson 4.3), and the rest of said is not used again, so the compiler is happy. If a later line tried to use said.text, you would get the same "use of moved value" error you met in chapter 4.

Try itYour turn: record a Message in Chatterbox

This is the whole Chatterbox program with the body of record taken out. Put it back: add the author, a colon and a space, the text, and a line break to the end of the transcript. The hidden tests compare the exact text the transcript ends up with.

This is the whole Chatterbox program with the body of record taken out. Put it back: add the author, a colon and a space, the text, and a line break to the end of the transcript. The hidden tests compare the exact text the transcript ends up with.

// 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, 5);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /say <text>, /quit";
 
/// One line of the conversation: who said it, and what they said.
struct Message {
author: String,
text: String,
}
 
/// Add one message to the transcript.
fn record(log: &mut String, msg: &Message) {
// add "author: text" and a line break to the end of log
todo!()
}
 
/// 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.
/// It only looks at the text, so it borrows it (&str) and never owns it.
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,
}
}
 
/// Everything after the first space, or "" when there is no space.
fn rest_of(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[i + 1..],
None => "",
}
}
 
/// 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 mut messages_seen: u32 = 0;
let quiet = false; // true skips the greeting
let mut last = String::new(); // the last thing you said, for /again
let mut transcript = String::new(); // everything said so far
 
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 first_word(message) {
"" => {} // nothing typed: nothing to answer
"/help" => println!("bot: {}", HELP),
"/quit" => {
println!("bot: bye, {}!", name);
break;
}
"/again" => {
if last.is_empty() {
println!("bot: nothing to repeat yet");
} else {
println!("bot: {}", reply(&last));
}
}
"/history" => {
if transcript.is_empty() {
println!("bot: nothing said yet");
} else {
print!("{}", transcript);
}
}
"/say" => println!("bot: {}", rest_of(message)),
_ => {
if is_command(message) {
println!(
"bot: I don't know the command {}. Try /help.",
first_word(message)
);
} else {
messages_seen += 1;
let said = Message {
author: String::from("you"),
text: String::from(message),
};
let answer = Message {
author: String::from("bot"),
text: reply(&said.text),
};
record(&mut transcript, &said);
record(&mut transcript, &answer);
println!("bot: {}", answer.text);
last = said.text; // the text moves out of `said`, which is not used again
}
}
}
}
println!("messages so far: {}", messages_seen);
}

Hidden tests (4): lines_pile_up_in_order empty_text_still_gets_its_line the_message_is_only_borrowed one_message_is_one_line

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
What does a struct give you that two loose strings do not?Reveal
One name and one owner for the pieces, so they travel together and cannot be mixed up by position.
Who owns the <code>text</code> inside a <code>Message</code>?Reveal
The message does. Move the message and the text moves with it; drop it and the text is freed.
Why does <code>record</code> take <code>&amp;Message</code> instead of <code>Message</code>?Reveal
It only needs to look. Borrowing lets the caller keep ownership and use the message afterwards.

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

Questions people ask

What is a struct in Rust?

A struct is a type you define that bundles several named values, called fields, into one thing. For example, a Message struct can hold an author and a text together.

How do I read a field of a struct in Rust?

Write the value, a dot, and the field name, such as m.author. If you only have a reference to the struct, the same dot works.

What does error E0063 missing field mean?

You built a struct value without giving every field a value. Rust has no automatic empty default, so add the missing field.

Does the order of fields matter when building a struct?

No. Fields are matched by name, so you can list them in any order and they still land in the right place.

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