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























