liveBook · Manning

String

As explained in Code Like a Pro in Rust

A string is a programming-language value representing an ordered sequence of characters or character units as text.

Rust’s core string types represent contiguous UTF-8 data. The practical choice is usually between `String`, which owns resizable heap storage, and `&str`, which borrows string data immutably. The reference may point into a `String` or to a string literal. section 4.1.1 section 4.1.2

Choose the interface by what the code needs:

  • Use `&str` for an argument that only reads text: callers can pass a literal or borrow a `String`. section 4.1.2
  • Use `String` when text must be mutable or resizable. Passing a `String` by value also permits moving its ownership. section 4.1.2
  • Use `&'static str` when a reference must remain valid for the process lifetime. An ordinary `String` cannot supply that lifetime. section 4.1.2

Do not treat `str` as a directly owned variable; work through a reference instead. Internally, `String` wraps `Vec<u8>` and dereferences to `str`. That layout explains why an owned string can provide an immutable string slice without making the slice own its data. section 4.1.2 section 4.3.2

Listing 4.1 Movable and nonmovable strings
fn print_String(s: String) {
    println!("print_String: {}", s);
}
 
fn print_str(s: &str) {
    println!("print_str: {}", s);
}
 
fn main() {
    // let s: str = "impossible str";       #1
    print_String(String::from("String"));   #2
    print_str(&String::from("String"));     #3
    print_str("str");                       #4
    // print_String("str");                 #5
}

The listing contrasts a function taking an owned `String` with one taking `&str`: the latter accepts both a borrowed `String` and a literal. section 4.1.2

Listing 4.6 Snippet of string.rs, from http://mng.bz/orAZ
pub struct String {
   vec: Vec<u8>,
}

The struct snippet shows the `Vec<u8>` field behind `String`. section 4.3.2

How Code Like a Pro in Rust covers it

How deep it goes
Explains allocation, borrowing, static lifetimes, and Vec<u8> backing, without developing UTF-8 encoding internals.
Examples
Contrasts functions accepting String and &str, then shows the Vec<u8> field inside String.
What it assumes
Assumes basic Rust syntax while explaining string borrowing and the meaning of a static lifetime.
What you can do after
Apply it via Rust’s standard library to select String, &str, or &'static str for storage and parameters.
How it connects
Connects strings to ownership, borrowing, lifetimes, slices, Vec, and the Deref trait.

Also explained in

Compare how 24 books explain string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.