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".
$ cargo run
/say|helloWhat does this print?
hellohelloello 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.
Step through the program. Solid arrows are ownership; dashed arrows are borrows. Use ← → or the slider.
- Line 1. The program starts in main.
- Line 2. msg owns ten bytes of text: the slash, three letters, a space and five letters.
- 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:&strborrows bytes 0..4 ofmsg. - Line 4. rest is a slice from position 5 to the end, hello. Position 4 is the space, which neither slice holds.
rest:&strborrows bytes 5..10 ofmsg. - Line 5. Both are read here, which is their last use, so both loans end. This prints /say|hello. stdout:
/say|hello - 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.
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_wordis the function you just met: the part before the first space, or the whole text when there is no space.rest_ofis its partner: everything after the first space, or""(empty text) when there is no space. The slice starts ati + 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.
Sam /say I am a robot /quit
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)
Download this version (zip)Unzip, then cargo run inside the folder.
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".
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.
Say it out loud, then reveal
What does &msg[0..4] give you?Reveal
Why can you not clear a String while a slice of it is still used?Reveal
What does a function signature fn first_word(text: &str) -> &str promise?Reveal
That is lesson 4.6. Tick it off so the course remembers where you are.
Go deeper
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.
Sources The Rust Book: The Slice Type