BorrowCheck › Rust language core

Strings and text

String vs &str, UTF-8 and indexing, chars/bytes/graphemes, formatting, OS and C strings.

The topic explains how Rust represents text: the owned String and the string slice &str, both holding UTF-8 encoded bytes. The questions check where each type belongs: why a &str parameter accepts a &String through deref coercion, why the + operator moves its left operand, what type the byte literal b"hi" has, and how parse relies on the FromStr trait. The UTF-8 subtopic covers why a string cannot be indexed by an integer, what len counts, when slicing across byte boundaries panics, and how the get method returns None instead. Bytes, char scalar values and graphemes are told apart: a combining mark is a character of its own, and a change of case can change the number of characters. The formatting subtopic covers the Display and Debug traits, width, precision and sign specifiers, inline capture of variables in a format string, and writing into a String with write!. The last subtopic deals with strings at the boundary with the operating system and C: OsStr, which need not be valid UTF-8, CString and its ban on an interior nul byte, c"..." literals, and Path, which compares paths by components.

39 questions: 21 basic, 14 intermediate, 4 advanced. 5 info pages, 20 sources.

Subtopics

  1. String vs &str
  2. UTF-8 and indexing
  3. Chars, bytes, graphemes
  4. Formatting, Display / Debug
  5. OsString, CString, Path

Previous: Structs, enums, pattern matching · Next: Traits, generics, dyn / impl