Sub topic 1
Two string types: &str and String
Rust has two main string types, and most beginner friction with text comes from mixing them up. &str is a borrowed view of text that someone else owns. String is an owned, growable buffer. This chapter explains how each is laid out in memory, how to convert between them, and how to pick one in your own code. Later chapters cover UTF-8 details, slicing rules, and formatting.
Prerequisites
This chapter assumes you know:
- Basic Rust syntax: variables, functions, and
println!. - Ownership and borrowing: moves, shared references (
&T), and mutable references (&mut T). OptionandResultat the level of reading amatchon them.
You do not need to know how UTF-8 works yet. For now, treat a string as "text that is valid UTF-8", and the next chapter explains what that means.
The core distinction
A str is a sequence of UTF-8 bytes of some length. It is an unsized type, so you cannot hold one directly in a variable. You always reach it through a pointer, almost always as &str, called a string slice.
A String is a struct that owns a heap buffer of UTF-8 bytes. It can grow, shrink, and change. When the String goes out of scope, its buffer is freed.
| Property | `&str` | `String` |
|---|---|---|
| Owns its bytes | No, it borrows them | Yes |
| Can grow or change | No | Yes, if declared `mut` |
| Size known at compile time | Yes (pointer and length) | Yes (pointer, length, capacity) |
| Typical source | Literals, slices of other strings | `String::from`, `format!`, reading input |
| Freed by | Whoever owns the underlying bytes | Its own `Drop` implementation |
You can see the layout difference by printing sizes. On a 64-bit target, &str is two machine words and String is three.
use std::mem::size_of;
fn main() {
println!("&str: {} bytes", size_of::<&str>());
println!("String: {} bytes", size_of::<String>());
}This prints 16 and 24. A &str stores a pointer and a length. A String stores a pointer, a length, and a capacity, which is how many bytes it can hold before it must reallocate.
Where string literals live
A literal such as "hello" has type &'static str. The bytes are stored in the compiled program's read-only data, so they exist for the whole run, and the 'static lifetime says so. The literal costs no heap allocation, and you cannot modify it.
fn main() {
let literal: &str = "hello";
let mut owned: String = String::from(literal);
owned.push('!');
owned.push_str(" world");
println!("{owned}");
}String::from(literal) allocates a heap buffer and copies the five bytes into it. After that, owned is independent of the literal. push appends one char and push_str appends a &str. Only String has these methods, because only String owns a buffer it can resize.
Slices borrow, they do not copy
Taking a slice of a String creates a &str that points into the same buffer. No bytes are copied. You can check this by comparing pointers.
fn main() {
let owned = String::from("hello world");
let first: &str = &owned[0..5];
println!("{first}");
println!("{}", first.as_ptr() == owned.as_ptr());
}This prints hello and then true. Because first borrows from owned, the borrow checker enforces two rules:
ownedmust stay alive as long asfirstis in use.- You cannot mutate
ownedwhilefirstis alive, since a push could reallocate the buffer and leavefirstpointing at freed memory.
If you try to call owned.push('!') and then print first, the compiler rejects the program. This is the mechanism behind many "cannot borrow as mutable" errors in text-processing code.
Converting between the two
Going from String to &str is cheap and often automatic. Going from &str to String allocates and copies, so Rust makes you ask for it.
| Goal | Expression | Cost |
|---|---|---|
| `&str` to `String` | `String::from(s)`, `s.to_string()`, `s.to_owned()`, `s.into()` | Allocate and copy |
| `String` to `&str` | `&owned`, `owned.as_str()`, `&owned[..]` | None |
| Format values into a `String` | `format!("{a}-{b}")` | Allocate |
All four ways of making a String from a &str give the same result. String::from and .to_owned() are common in library code, and .to_string() is common in application code. Pick one and stay consistent within a project.
Passing a String to a function by value moves it, so the caller can no longer use it:
fn consume(s: String) -> usize {
s.len()
}
fn main() {
let a = String::from("moved");
let n = consume(a);
println!("{n}");
}Using a after the call to consume is a compile error ("borrow of moved value"). If consume only needed to read the text, taking String would be the wrong signature. That leads to the main design rule.
Choosing a type for function signatures
Use these defaults:
- Read-only parameter: take
&str. It accepts string literals,&String, and slices of either. - Function that stores or changes the text: take
Stringif the function needs to keep it. The caller then decides whether to clone or give up its own copy. - Return value: return
Stringwhen the function creates new text. Return&stronly when the result is a slice of an input, and the lifetimes make that clear.
fn shout(s: &str) -> String {
s.to_uppercase()
}
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let owned = String::from("hi there");
println!("{}", shout(&owned));
println!("{}", shout("literal"));
println!("{}", first_word(&owned));
}shout(&owned) passes a &String, and the function expects &str. This works because of deref coercion. String implements Deref<Target = str>, so the compiler automatically converts &String to &str wherever a &str is expected. A parameter typed &String would be strictly worse. It rejects literals and slices, and it gains nothing.
first_word returns a slice of its input. The compiler infers that the returned reference lives no longer than s. A function that tried to build a String locally and return a &str to it would fail to compile with "cannot return reference to local variable", because the buffer is freed when the function returns.
Common errors
- "expected
&str, foundString": you passed an owned value where a borrow is expected. Add&. - "expected
String, found&str": you passed a literal where ownership is required. UseString::from("...")or.to_string(). - "cannot borrow as mutable": you called
push_stron a variable not declaredmut, or while a&strslice of it is still in use. - "borrowed value does not live long enough": a
&stroutlived theStringit points into, often by being returned or stored in a longer-lived struct. - Needless cloning: calling
.to_string()just to satisfy a signature that could be&str. Change the signature instead.
What comes next
This chapter fixed the vocabulary: &str borrows, String owns, and String derefs to &str. The next chapter looks inside both types at the UTF-8 encoding that every str is guaranteed to hold.
Exercise
A function fn count_vowels(s: &String) -> usize compiles, but calling count_vowels("audio") fails. Explain why, and show the signature you would use instead.
Show answer
A string literal has type &'static str, not &String, and deref coercion only converts &String to &str, not the other direction. Change the parameter to fn count_vowels(s: &str) -> usize. It then accepts literals, &String (through deref coercion), and slices of either.
Exercise
In this code, why does the compiler reject the last line, and how would you fix it? let mut s = String::from("abc"); let t: &str = &s[0..2]; s.push('d'); println!("{t}");
Show answer
t borrows from the buffer of s. Calling s.push('d') needs a mutable borrow while t is still used afterward, and a push could reallocate the buffer and leave t dangling. Fix it by finishing with t before pushing (print it first), or by copying with let t = s[0..2].to_string(); so t owns its own bytes.