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.2 · 8 min

Giving a struct behaviour

A Message can hold an author and a text, but everything you do with one still lives in loose functions. An impl block puts the actions next to the data they act on.

Adds to ChatterboxMessage methods, and /shout.

Functions that live with the struct

In lesson 5.1 you wrote record(log, msg), a loose function that takes a borrowed &Message. An impl block lets you attach functions like that to the type itself, so they are called with a dot: msg.shout(). Same borrowing rules as chapter 4; just a tidier address.

Two kinds of thing go in an impl. A function without self, like new, is called on the type: Message::new(..). The :: is the same path separator as in String::from: it reads "the new that belongs to Message". Rust calls this an associated function. A function whose first parameter is self is a method, called on a value.

new builds one, shout and is_empty only look
struct Message {
author: String,
text: String,
}
 
impl Message {
fn new(author: &str, text: &str) -> Message {
Message { author: String::from(author), text: String::from(text) }
}
 
fn shout(&self) -> String {
self.text.to_uppercase()
}
 
fn is_empty(&self) -> bool {
self.text.trim().is_empty()
}
}
 
fn main() {
let m = Message::new("you", "hello there");
println!("{}", m.shout());
println!("{}", m.is_empty());
}
$ cargo run
HELLO THERE
false

&self is shorthand for "borrow this message, read only". Inside the method, self.text is the field. The caller keeps the key, which is why you can call shout and then is_empty on the same m.

A method that needs to change the message says &mut self, the exclusive borrow from lesson 4.5.

A &mut self method on a binding that is not mut
struct Message {
author: String,
text: String,
}
 
impl Message {
fn new(author: &str, text: &str) -> Message {
Message { author: String::from(author), text: String::from(text) }
}
 
fn clear(&mut self) {
self.text.clear();
}
}
 
fn main() {
let m = Message::new("you", "oops");
m.clear();
println!("{}", m.author);
}
error[E0596]: cannot borrow `m` as mutable, as it is not declared as mutable
  --> src/main.rs:18:5
   |
18 |     m.clear();
   |     ^ cannot borrow as mutable
   |
help: consider changing this to be mutable
   |
17 |     let mut m = Message::new("you", "oops");
   |         +++

E0596: "cannot borrow m as mutable, as it is not declared as mutable". Calling clear quietly takes a &mut borrow of m, and you never said m could change. The fix is the same word as in lesson 2.2: let mut m.

So the signature is a promise you can read from outside. &self: looks only. &mut self: may change it. self with no &: the method receives the key itself, so the caller has given the message away and cannot use it afterwards (the move from lesson 4.3).

PredictCall a method twice
struct Message {
text: String,
}
 
impl Message {
fn shout(&self) -> String {
self.text.to_uppercase()
}
}
 
fn main() {
let m = Message { text: String::from("hi") };
let a = m.shout();
let b = m.shout();
println!("{a}{b}{}", m.text);
}

What does this print?

  • HIHIhi
  • HIHI
  • it does not compile
Reveal the answer

The program prints: HIHIhi shout borrows with &self and returns a brand-new String. The original m.text is untouched and m is still usable, so you can call it as often as you like.

Chatterbox v0.5: Message grows methods, and /shout

Here is the whole program after this lesson, with the new lines in green. Message gets an impl block with three functions:

  • Message::new("you", message) builds a message from two borrowed pieces of text. The loop used to spell out Message { author: String::from("you"), … } twice; now it says what it means in one short call.
  • to_line(&self) turns a message into one transcript line, you: hello. record now just asks the message for its line instead of gluing the pieces together itself.
  • shout(&self) returns the text in capitals, a brand-new String. All three only look, so none of them needs &mut self.

And Chatterbox learns a new command. /shout hello there takes the words after the command (with rest_of, from lesson 4.6), wraps them in a Message just long enough to call .shout() on it, and prints the result. The help text lists it too.

Chatterbox v0.5 after lesson 5.2: the whole program (green lines are new in this lesson)
You type
Sam
/shout hello there
/quit
Chatterbox prints (a real run)
Chatterbox v0.5
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: HELLO THERE
bot: bye, Sam!
messages so far: 0
Show the whole program (open it after you have tried the exercise below: it contains the answer)
src/main.rs22 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>, /shout <text>, /quit";
 
/// 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()
}
}
 
/// Add one message to the transcript.
fn record(log: &mut String, msg: &Message) {
log.push_str(&msg.to_line());
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)),
"/shout" => println!("bot: {}", Message::new("you", rest_of(message)).shout()),
_ => {
if is_command(message) {
println!(
"bot: I don't know the command {}. Try /help.",
first_word(message)
);
} else {
messages_seen += 1;
let said = Message::new("you", message);
let answer = Message::new("bot", &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);
}

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

Try itWarm-up: word_count and append

A small warm-up first, on a cut-down Message with only a text. It practises the one kind of method Chatterbox does not use yet, &mut self. Fill in both methods. word_count only looks and returns how many words are in the text: split_whitespace() splits text into words and .count() counts what it gives you. The count is a usize, a whole number used for sizes and positions. append changes the message: it adds a space and then the extra text to the end.

A small warm-up first, on a cut-down Message with only a text. It practises the one kind of method Chatterbox does not use yet, &mut self. Fill in both methods. word_count only looks and returns how many words are in the text: split_whitespace() splits text into words and .count() counts what it gives you. The count is a usize, a whole number used for sizes and positions. append changes the message: it adds a space and then the extra text to the end.

struct Message {
text: String,
}
 
impl Message {
fn word_count(&self) -> usize {
// count the words in self.text
0
}
 
fn append(&mut self, extra: &str) {
// add a space, then extra, to the end of self.text
}
}
 
fn main() {
let mut m = Message { text: String::from("hello big") };
m.append("world");
println!("{} words", m.word_count());
}

Hidden tests (4): append_joins_with_a_space append_then_count counts_words empty_has_no_words

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

Try itYour turn: Message methods in Chatterbox

Now the real thing. This is the whole Chatterbox program with the bodies of Message::new, to_line and shout taken out. Put all three back. The hidden tests build messages, read their lines and shout them, including empty text and mixed capitals.

Now the real thing. This is the whole Chatterbox program with the bodies of Message::new, to_line and shout taken out. Put all three back. The hidden tests build messages, read their lines and shout them, including empty text and mixed capitals.

// 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>, /shout <text>, /quit";
 
/// 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 {
// build a Message that owns its own copy of both pieces of text
todo!()
}
 
/// The message as one transcript line: "you: hello".
fn to_line(&self) -> String {
// "you: hello"
todo!()
}
 
/// The text in capitals, for /shout.
fn shout(&self) -> String {
// the text in capitals
todo!()
}
}
 
/// Add one message to the transcript.
fn record(log: &mut String, msg: &Message) {
log.push_str(&msg.to_line());
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)),
"/shout" => println!("bot: {}", Message::new("you", rest_of(message)).shout()),
_ => {
if is_command(message) {
println!(
"bot: I don't know the command {}. Try /help.",
first_word(message)
);
} else {
messages_seen += 1;
let said = Message::new("you", message);
let answer = Message::new("bot", &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 (7): new_fills_both_fields record_uses_the_line shout_handles_mixed_case shout_leaves_the_message_alone shout_of_nothing_is_nothing to_line_is_author_colon_text to_line_with_empty_text

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 is the difference between <code>Message::new(..)</code> and <code>m.shout()</code>?Reveal
new has no self, so it is called on the type and builds a value. shout takes &self, so it is called with a dot on a value that exists.
Why did <code>m.clear()</code> fail with E0596?Reveal
clear needs &mut self, an exclusive borrow, and m was not declared mut.
What does <code>&amp;self</code> promise the caller?Reveal
The method only reads the value. The caller keeps ownership and can use the value again afterwards.

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

Questions people ask

What is an impl block in Rust?

An impl block holds the functions that belong to a type. Writing impl Message { ... } attaches those functions to Message, so you can call them with a dot or with Message::.

What is self in a Rust method?

self is the value the method was called on. &self borrows it to read, &mut self borrows it to change, and plain self takes ownership of it.

What is the difference between a method and an associated function?

A method has self as its first parameter and is called on a value, like m.shout(). An associated function has no self and is called on the type, like Message::new().

What does error E0596 mean in Rust?

You tried to change something, or borrow it with &mut, that was not declared mutable. Add mut where the variable is made, as in let mut m.

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