Sub topic 1
Two string types: &str and String
Rust has two main string types. &str is a borrowed view of text. String is an owned, growable buffer of text. This chapter explains how they differ and when to use each. Later chapters cover UTF-8, slicing, and the other string types in detail.
Prerequisites
This chapter assumes you know the following:
- Basic Rust syntax: variables, functions, and
println!. - Ownership and borrowing basics, including what
&andmutmean. - How
OptionandResultwork.
The working model
A &str (a "string slice") is a reference to UTF-8 text stored somewhere else. It holds a pointer and a length. It does not own the bytes, so it cannot grow or change them.
A String owns a heap-allocated buffer of UTF-8 bytes. It holds a pointer, a length, and a capacity. It frees the buffer when it goes out of scope, and it can grow.
| Feature | `&str` | `String` |
|---|---|---|
| Ownership | Borrowed | Owned |
| Mutable size | No | Yes, if declared `mut` |
| Storage | Anywhere: binary, heap, stack | Heap |
| Typical use | Parameters, literals, views | Building and storing text |
String literals such as "hello" have the type &'static str. The text is stored in the compiled program and lives for the whole run.
Converting between them
The first example turns a literal into an owned String, then changes it.
fn main() {
let literal: &str = "hello";
let mut owned: String = String::from(literal);
owned.push('!');
owned.push_str(" world");
println!("{owned}");
}String::from copies the bytes into a new heap buffer. push appends one char. push_str appends a &str. The program prints hello! world.
Going the other way is cheap. Borrowing a String with & gives you a &str view of the same bytes, with no copy.
Choosing between them
Use these rules as a starting point:
- Take
&strfor function parameters that only read text. Callers can pass literals and borrowedStringvalues. - Return
Stringwhen the function creates new text, because the caller needs to own it. - Store
Stringin structs when the struct must own its data. Store&stronly when you can name a lifetime that outlives the struct.
fn shout(s: &str) -> String {
s.to_uppercase()
}
fn main() {
let owned = String::from("hi");
println!("{}", shout(&owned));
println!("{}", shout("there"));
}shout(&owned) passes a &String. Rust converts it to &str automatically. This is called deref coercion, and a later chapter covers it.
Common errors
- Expecting a
&strto grow. Callingpush_stron a&strdoes not compile because the type has no such method. Convert toStringfirst. - Passing a
&strwhereStringis required. The compiler reports a type mismatch. Call.to_string(),String::from, or.to_owned()to make an owned copy. - Forgetting
mut.pushandpush_strneed amutbinding. - Returning a
&strto a localString. TheStringis freed when the function ends, so the reference would dangle. The borrow checker rejects this. Return theStringinstead.
Exercise
A function fn greet(name: String) is called as greet("Ana"). It fails to compile. Give two ways to fix this, and say which is better for a function that only reads name.
Show answer
Either call greet(String::from("Ana")), which makes the caller allocate, or change the signature to fn greet(name: &str). Changing the signature is better for a read-only function, because callers can pass literals and &String values without allocating.