Skip to content
Tutorials Center
My learning

Topics

Rust Reference · Strings and Text

Rust String type

Reference for Rust's String type: an owned, growable UTF-8 buffer, how it differs from &str, how to build, grow, slice and convert it, with examples.

String is Rust's owned, growable text type. It stores its characters on the heap as UTF-8 bytes and is essentially a Vec<u8> with a promise that the bytes are always valid UTF-8. You use String when you need to own text, build it piece by piece, or return it from a function; you use &str when you only need to look at text.

String dereferences to str, so every str method (len, trim, split, contains, ...) works directly on a String. Passing &String where &str is expected also works through deref coercion, which is why functions that only read text should accept &str.

Rust
let mut s = String::from("hello");
s.push_str(", world");
s.push('!');

Try it

Rust Owning, growing and borrowing

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Slicing, indexing and UTF-8

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub struct String { /* a Vec<u8> that is always valid UTF-8 */ }

let a: String = String::new();
let b: String = "text".to_string();
let c: &str = &b;           // deref coercion
Group Methods
Create new, with_capacity, from, to_string, to_owned, format!, from_utf8 (details)
Grow push, push_str, insert, insert_str, extend, +, += (details)
Shrink pop, remove, truncate, clear, drain, retain (details)
Size len, is_empty, capacity, reserve, shrink_to_fit (details)
Inherited from str trim, split, find, replace, parse, chars, bytes, to_uppercase, ...

Returns / panics: methods that take byte offsets (insert, remove, truncate, slicing with [..]) panic if the offset is not on a char boundary or is out of range. The get family returns Option instead.

Usage notes

  • String versus &str: String owns and can grow; &str borrows a view into some UTF-8 data (a literal, a String, part of either). Take &str in parameters; return String when the function creates new text.
  • Indexing by integer is not allowed. s[0] does not compile because a position in a UTF-8 string is ambiguous (byte, scalar value, grapheme). Use .chars().nth(i), .bytes(), or a range slice on a known boundary.
  • Length is in bytes. "é".len() is 2 and "日本".len() is 6. Count characters with chars().count(); note that even chars are not always what a user sees as one letter (combining marks, emoji sequences).
  • Memory layout: a String is three words (pointer, length, capacity) on the stack with the text on the heap. Cloning copies the text.
  • Capacity growth is amortized. Repeated push_str is cheap; if you know the final size, call with_capacity or reserve to avoid reallocations.
  • + consumes its left operand: a + &b moves a. Use format! or push_str in loops and when you want to keep every piece.
  • Invalid UTF-8 cannot live in a String. For arbitrary bytes use Vec<u8>; to convert, use String::from_utf8 or from_utf8_lossy. File names and environment values that may not be UTF-8 use OsString.
  • Traits: String implements Display, Debug, Clone, Default, Hash, Ord, FromStr, FromIterator<char>, Extend, Write (via fmt::Write), Borrow<str>, and more. Because of Borrow<str>, a HashMap<String, V> can be looked up with a &str.