Vibe Engines
YouTube

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

Learn RustChapter 4: Memory

Lesson 4.6 · 11 min

Parts of a value

Chatterbox should understand "/say hello" as a command and its text. A slice is a borrowed window onto part of a String, and it follows every rule you have already learned.

Adds to Chatterbox/say: slices pull a command apart.

A window onto part of a value

Chatterbox gets commands like /say hello. To react, it must treat /say as the command and hello as the text to say. You could build two new Strings, but each would copy text that is already there. Rust has a better idea: a slice is a borrowed window onto part of the text.

You write it with &, then the value, then a range in square brackets. Counting starts at 0 and the end is not included, so [..4] is "from the start up to position 4".

Two slices of one String, and no copying
fn main() {
let msg = String::from("/say hello");
let cmd = &msg[..4];
let rest = &msg[5..];
println!("{cmd}|{rest}");
}
$ cargo run
/say|hello
PredictWhich part is it?
fn main() {
let s = String::from("hello world");
println!("{}", &s[0..5]);
}

What does this print?

  • hello
  • hello
  • ello w
Reveal the answer

The program prints: hello The range 0..5 takes positions 0 up to but not including 5: h, e, l, l, o. The space is at position 5, so it stays out.

Watch what a slice is made of. It is a &str, the 16-byte pointer and length from lesson 4.1: it points into the owner's heap text and says "from here, this many bytes". The same text has one owner and two borrowers, and nothing was copied. You have met slices before without the name: in lesson 4.1's table, name and message were exactly this, the slices that trim() hands back.

One sharp edge: the positions count bytes, not letters (lesson 2.5). Plain letters and spaces are one byte each, but an emoji or a letter like é takes several. If a slice starts or ends at a byte position that falls in the middle of such a character, the program stops with a panic. That is why this course finds positions with methods like find instead of guessing numbers: find always lands on the edge of a character.

Ownership Stagecmd and rest are borrowed windows onto msg

Step through the program. Solid arrows are ownership; dashed arrows are borrows. Use ← → or the slider.

fn main() {
let msg = String::from("/say hello");
let cmd = &msg[..4];
let rest = &msg[5..];
println!("{cmd}|{rest}");
}
  1. Line 1. The program starts in main.
  2. Line 2. msg owns ten bytes of text: the slash, three letters, a space and five letters.
  3. Line 3. cmd is a slice of the first four bytes, /say: a pointer to byte 0 of msg's heap text and a length of 4. It is a borrow: it points at part of the text and owns nothing. cmd: &str borrows bytes 0..4 of msg.
  4. Line 4. rest is a slice from position 5 to the end, hello. Position 4 is the space, which neither slice holds. rest: &str borrows bytes 5..10 of msg.
  5. Line 5. Both are read here, which is their last use, so both loans end. This prints /say|hello. stdout: /say|hello
  6. Line 6. main ends and msg's text is cleaned up once.

A slice is a borrow, so the old rules hold

That sounds like a footnote, and it is the most useful consequence in the lesson. Because cmd is a loan, the owner may not change msg while cmd is still going to be used. If it did, the window could point at text that has been rewritten or removed. Here is the same mistake in lesson 4.4 shape, with a function returning the slice.

A slice keeps the loan alive. clear() wants to change the owner.
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[..i],
None => text,
}
}
 
fn main() {
let mut msg = String::from("/say hello");
let cmd = first_word(&msg);
msg.clear();
println!("{cmd}");
}
error[E0502]: cannot borrow `msg` as mutable because it is also borrowed as immutable
  --> src/main.rs:11:5
   |
10 |     let cmd = first_word(&msg);
   |                          ---- immutable borrow occurs here
11 |     msg.clear();
   |     ^^^^^^^^^^^ mutable borrow occurs here
12 |     println!("{cmd}");
   |                --- immutable borrow later used here

In the code above, text.find(' ') asks where the first space is (the space is in single quotes because it is one character, not a piece of text). The answer is Some(i), carrying the space's position i, or None when there is no space. So the match reads as two cases: found at i, or not found.

Read the signature: fn first_word(text: &str) -> &str. There is one borrowed input and one borrowed output. Rust reads that as "the result is a window into the input", which is exactly what the code does, so the output is a loan of msg too. You do not have to write anything more for that. (The Rust Book calls this idea lifetimes; ignore the word for now.)

Finishing with cmd before clear is the fix, as in lesson 4.4. The message, from the owner's point of view, is read-only while a window onto it is still in use.

Chatterbox v0.4: /say

Chatterbox gets two small helpers that cut a message at its first space, and both hand back slices, so not a byte is copied.

  • first_word is the function you just met: the part before the first space, or the whole text when there is no space.
  • rest_of is its partner: everything after the first space, or "" (empty text) when there is no space. The slice starts at i + 1, one past the space, so the space itself is left out.

With them, the match in main changes what it looks at: match first_word(message) instead of the whole message. A lone command such as /help is its own first word, so every arm you had still fits. A new arm, "/say" =>, answers with rest_of(message), word for word: /say I am a robot makes it answer bot: I am a robot. The catch-all becomes _, the nameless catch-all from lesson 3.2, because a name there would hold only the first word, and the arm wants the whole message: an unknown command is named by its first word, and an ordinary message is counted, copied into said, answered, recorded and kept, exactly as before. The help text grows to commands: /help, /again, /history, /say <text>, /quit, where <text> means "whatever you want it to say".

One honest gap: /say with nothing after it makes Chatterbox say nothing at all, a lonely bot:. Chapter 5 teaches it a better answer. That closes chapter 4: Chatterbox keeps a transcript, remembers your last message, and pulls a command apart without copying a byte.

Chatterbox v0.4 after lesson 4.6: the whole program (green lines are new in this lesson)
You type
Sam
/say I am a robot
/quit
Chatterbox prints (a real run)
Chatterbox v0.4
What should I call you?
Hi Sam! I'm Chatterbox. Ask me anything.
bot: I am a robot
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.rs24 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, 4);
/// 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";
 
/// 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 => "",
}
}
 
/// Add one line to the transcript. `log` is borrowed mutably (&mut):
/// this function may change it, and nobody else can touch it meanwhile.
fn record(log: &mut String, who: &str, text: &str) {
log.push_str(who);
log.push_str(": ");
log.push_str(text);
log.push('\n');
}
 
/// 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 = String::from(message);
let answer = reply(&said);
record(&mut transcript, "you", &said);
record(&mut transcript, "bot", &answer);
println!("bot: {}", answer);
last = said;
}
}
}
}
println!("messages so far: {}", messages_seen);
}

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

Try itYour turn: pull a command apart in Chatterbox

This is Chatterbox v0.4 with one line missing from each of first_word and rest_of. The match on find(' ') is already there, and so is the not-found case. Replace each todo!() with a slice of text, never a new String. Only the FIRST space splits: "/say hi" (two spaces) has the rest " hi".

This is Chatterbox v0.4 with one line missing from each of first_word and rest_of. The match on find(' ') is already there, and so is the not-found case. Replace each todo!() with a slice of text, never a new String. Only the FIRST space splits: "/say hi" (two spaces) has the rest " hi".

// 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, 4);
/// 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";
 
/// 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) => todo!(), // the slice before the space
None => text,
}
}
 
/// Everything after the first space, or "" when there is no space.
fn rest_of(text: &str) -> &str {
match text.find(' ') {
Some(i) => todo!(), // the slice after the space
None => "",
}
}
 
/// Add one line to the transcript. `log` is borrowed mutably (&mut):
/// this function may change it, and nobody else can touch it meanwhile.
fn record(log: &mut String, who: &str, text: &str) {
log.push_str(who);
log.push_str(": ");
log.push_str(text);
log.push('\n');
}
 
/// 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 = String::from(message);
let answer = reply(&said);
record(&mut transcript, "you", &said);
record(&mut transcript, "bot", &answer);
println!("bot: {}", answer);
last = said;
}
}
}
}
println!("messages so far: {}", messages_seen);
}

Hidden tests (5): no_space_means_no_rest only_the_first_space_splits splits_a_command_from_its_text empty_text works_on_a_borrowed_string

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 &msg[0..4] give you?Reveal
A borrowed slice of the first four bytes of msg. Nothing is copied and msg keeps its ownership.
Why can you not clear a String while a slice of it is still used?Reveal
The slice is a borrow. Changing the owner while the loan is live is refused with E0502.
What does a function signature fn first_word(text: &str) -> &str promise?Reveal
That the result is a window into the input, so the caller must keep the input alive and unchanged while it uses the result.

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

Questions people ask

What is a string slice in Rust?

A string slice, written &str, is a borrowed view of part or all of some text. It points into text that someone else owns, so making one copies nothing.

How do I get part of a String in Rust?

Write & then the String then a range in square brackets, such as &msg[0..4] for the first four bytes. The end of the range is not included.

Why does slicing a string panic in Rust?

The positions count bytes, and some characters such as emoji or accented letters take several bytes. Slicing in the middle of one of them stops the program, so find positions with methods like find instead of guessing.

How do I get the first word of a string in Rust?

Find the position of the first space with find, then slice from the start up to that position. If there is no space, the whole text is the first word.

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