Vibe Engines
YouTube

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

Learn RustChapter 2: Values

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.

Turn fixed text into a String, then grow it
fn main() {
let mut message = String::from("Hello");
message.push_str(", world");
message.push('!');
println!("{}", message);
}
$ 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.

Fixed text is not a String
fn main() {
let greeting: String = "Hello";
println!("{}", greeting);
}
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.

PredictHow long is it?
fn main() {
let word = "héllo";
println!("{}", word.len());
}

What does this print? Remember that len() counts bytes, not letters.

  • 5
  • 6
  • 4
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 after lesson 2.5: the whole program (green lines are new in this lesson)
src/main.rs3 new lines
// Chatterbox: a small chat program, built one lesson at a time.
 
/// The first line Chatterbox prints.
fn banner(bot: &str, version: &str) -> String {
format!("{} v{}", bot, version)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str, bot: &str) -> String {
let mut text = format!("Hi {}! I'm {}.", name, bot);
text.push_str(" Ask me anything.");
text
}
 
fn main() {
let name = "Sam";
let bot = "Chatterbox";
let version = "0.2";
// u32: a whole number that is never negative and fits in 4 bytes,
// so it can count past four billion messages before it runs out.
let mut messages_seen: u32 = 0;
let max_len: usize = 200; // the longest message we accept, in bytes
let quiet = false; // true would skip the greeting
 
println!("{}", banner(bot, version));
println!("{}", greeting(name, bot));
println!("(limit: {} bytes a message, quiet: {})", max_len, quiet);
 
// The greeting was our first message, so the count goes up by one.
messages_seen += 1;
println!("messages so far: {}", messages_seen);
}
Chatterbox prints (a real run)
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.

Try itYour turn: label a message

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.

fn labelled(message: &str) -> String {
let mut line = String::from("you: ");
// add the message to the end of line
line
}
 
fn main() {
println!("{}", labelled("hello"));
}

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.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What is the difference between a &str and a String?Reveal
A &str is a read-only view of text stored somewhere else, such as quoted text in the program or part of a String. A String is text the program owns and can grow.
How do you turn fixed text into a String?Reveal
String::from("text") or "text".to_string(). Both copy the text into a new String you own.
What does len() count for text?Reveal
Bytes, not letters. An accented letter is more than one byte.

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

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.

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