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.
let mut s = String::from("hello"); s.push_str(", world"); s.push('!');
Try it
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.
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
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
Stringversus&str:Stringowns and can grow;&strborrows a view into some UTF-8 data (a literal, aString, part of either). Take&strin parameters; returnStringwhen 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 withchars().count(); note that evenchars are not always what a user sees as one letter (combining marks, emoji sequences). - Memory layout: a
Stringis three words (pointer, length, capacity) on the stack with the text on the heap. Cloning copies the text. - Capacity growth is amortized. Repeated
push_stris cheap; if you know the final size, callwith_capacityorreserveto avoid reallocations. +consumes its left operand:a + &bmovesa. Useformat!orpush_strin loops and when you want to keep every piece.- Invalid UTF-8 cannot live in a
String. For arbitrary bytes useVec<u8>; to convert, useString::from_utf8orfrom_utf8_lossy. File names and environment values that may not be UTF-8 useOsString. - Traits:
StringimplementsDisplay,Debug,Clone,Default,Hash,Ord,FromStr,FromIterator<char>,Extend,Write(viafmt::Write),Borrow<str>, and more. Because ofBorrow<str>, aHashMap<String, V>can be looked up with a&str.