Rust Tutorial: Strings
String slices and owned Strings, concatenation, formatting, and common string methods.
Two kinds of strings
- `&str` — an immutable string slice. Lightweight, borrowed.
- `String` — an owned, growable, heap-allocated string.
Knowing when to use each is one of the most common beginner questions. This chapter answers it.
What you'll learn in this Rust strings tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- String literals are &str — String literals are `&str` — references to text embedded in the binary. Immutable and fixed-size.
- Owned String — `String::from()` creates a heap-allocated string you can grow and modify.
- push a character — `push` appends a single `char`. `push_str` appends a string slice.
- format! macro — `format!` creates a new String from parts without printing.
- Common string methods — Strings have many built-in methods.
- Splitting strings — `split()` returns an iterator of string slices. Collect it into a Vec.
- starts_with and ends_with — Check the beginning or end of a string:
- Convert to String and back — `.to_string()` converts anything printable to a String. `.parse()` goes the other way.
Rust Strings concepts covered
- Two kinds of strings