Lesson 2.5 · 9 min
Text: String and &str
Text is the one value Chatterbox cannot live without, and Rust has two kinds of it. One is a view you can read but not change. The other is text your program owns and can grow. Knowing which is which ends the most common beginner stumble.
Adds to ChatterboxThe greeting is built up as text.
Two kinds of text
Every quoted piece of text you have written so far, like "Chatterbox", is a &str (say "string slice"). A &str is a view of some text that is stored somewhere else: you can read it, but you cannot grow or change it through the view. Quoted text is the simplest case: it is baked into your program, and the &str lets you look at it. (A &str can also look at all or part of a String, which you meet in a moment.) The & in front is a hint that you are looking at, not holding. Chapter 4 explains that fully, so treat this as a preview; for now read &str as "text I can read".
The other kind is String. This is text your program owns and can change: add to the end, build up piece by piece, hold something typed by a user. Chatterbox needs this for messages, because a message is not known when you write the code.
$ cargo run
Hello, world!String::from("Hello") copies the quoted text into a new String that your program owns. push_str adds more text on the end, and push adds one character. Notice the quotes: double quotes, "text", make a piece of text of any length, while single quotes, '!', make exactly one character (its type is called char). One character is written specially: \n, a backslash and an n, stands for the newline character, the invisible character that ends a line, so "one\ntwo" prints on two lines. (A function that belongs to a value and is used with a dot after it, like message.push_str(…), is called a method. You will meet many more.) Because the text changes, the name needs let mut, exactly as in lesson 2.2.
The compiler keeps them apart
The two kinds are different types, so one cannot quietly stand in for the other.
error[E0308]: mismatched types --> src/main.rs:2:28 | 2 | let greeting: String = "Hello"; | ------ ^^^^^^^ expected `String`, found `&str` | | | expected due to this | help: try using a conversion method | 2 | let greeting: String = "Hello".to_string(); | ++++++++++++
"mismatched types", the same E0308 you fixed in lesson 1.5: the name was promised to be a String but the value is a &str. The help text suggests .to_string(). Both .to_string() and String::from do the same job: make an owned String from a &str.
The other direction is free. Anywhere a function wants a &str, you can hand it a String by writing & in front: the function gets a view of that String's text. That is why Chatterbox's functions, like greeting(name: &str, …), take &str: they accept quoted text and Strings alike.
Combining text
You have met format!. It builds a new String from pieces and leaves the originals alone, so it is usually the cleanest way to join text.
What does this print? Remember that len() counts bytes, not letters.
564
Reveal the answer
The program prints: 6 The letter e with an accent takes two bytes in UTF-8, the encoding Rust uses for text, so five letters are six bytes. len() reports bytes. Counting letters is a different method, chars().count(), and you will not need it yet.
Chatterbox v0.2: a greeting that grows
Time to use a String in Chatterbox. Until now greeting was one format! line. Now it builds the text in two steps, the way you build a message in real life: start with the hello, then add to it.
Chatterbox v0.2 Hi Sam! I'm Chatterbox. Ask me anything. (limit: 200 bytes a message, quiet: false) messages so far: 1
Download this version (zip)Unzip, then cargo run inside the folder.
Follow the greeting through the green lines inside greeting. let mut text = format!(…) builds Hi Sam! I'm Chatterbox. as a String and names it text, with mut because it is about to change. text.push_str(" Ask me anything."); adds an invitation to the end. The last line, text on its own with no semicolon, is the last expression from lesson 1.6, so the grown String is what the function hands back.
The invitation replaces the separate Type a message and I will answer. line that main used to print, so that println! is gone and the greeting is one line that says both things. Everything else is unchanged: the banner, the settings line, and the counter typed as a u32 in lesson 2.4.
Later on, Chatterbox keeps a history that shows each line you typed as you: hello. Build that label now. Make labelled return you: followed by the message. Start from the String that is already there and grow it.
Later on, Chatterbox keeps a history that shows each line you typed as you: hello. Build that label now. Make labelled return you: followed by the message. Start from the String that is already there and grow it.
Hidden tests (3): different_messages_differ labels_a_message empty_message
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
What you have now
Chatterbox v0.2 has names, a counter with a size, a limit, a switch and a greeting that grows. One thing still bothers: bot and version are passed into every function that needs them, although they never change while the program runs. The last lesson of this chapter gives fixed facts like those a better home.
Say it out loud, then reveal
What is the difference between a &str and a String?Reveal
How do you turn fixed text into a String?Reveal
What does len() count for text?Reveal
That is lesson 2.5. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
When should I use String and when &str?
Use &str for text you only read, such as function inputs. Use String when you need to own, build or change text.
Why does Rust have two string types?
A &str is a read-only view that is cheap to pass around; a String owns its text and can grow. Keeping them as separate types makes it clear which you are holding.
What does the & in &str mean?
It marks a reference: the text is borrowed from somewhere else. Chapter 4 explains borrowing.