Topic
String vs &str
Rust has two string types.
String owns its data on the heap and can grow. &str is a borrowed slice — a read-only view into existing text. Knowing which one to use and how to convert between them is one of the most common early Rust questions.Quick Reference
| Concept | What it means |
|---|---|
| String | Heap-allocated, owns its data, can grow and shrink, mutable with mut |
| &str | String slice — an immutable borrowed view into a string. Read-only. |
| String literal | Text in double quotes, type &str, stored in read-only memory at compile time |
| push_str | Appends a string slice (&str) to a String |
| push | Appends a single character to a String |
| to_string() / String::from() | Convert &str to String — copies text into new heap memory |
| &s on a String | Converts String to &str automatically when a function expects it |
| Term | What it means | When you use it |
|---|---|---|
| String | Heap-allocated, owns its data, can grow and shrink | When you need to build or modify text at runtime |
| &str | Immutable borrowed view into a string | When you only need to read text, not own it |
| String literal | Text in double quotes, type &str, baked into the binary | When writing fixed text directly in your code |
| push_str | Appends a string slice to a String | Adding multiple characters at once to a String |
| push | Appends a single character to a String | Adding one character at a time |
| to_string() / String::from() | Convert &str to owned String | When you need to own the text data |
| &s / as_str() | Convert String to &str | Passing a String to a function that expects &str |
| + | Concatenates String with &str — the left String is consumed | Joining two strings into one new value |