String Slices and &str

Updated

October 31, 2026

String Slices and &str

A string slice is a reference to a contiguous sequence of UTF-8 encoded bytes in a String.

fn main() {
    let s = String::from("Hello Rust");

    let first_word = &s[0..5];
    let second_word = &s[6..10];

    println!("First: {}, Second: {}", first_word, second_word);
}

String vs &str

  • String: Owned, heap-allocated, resizable buffer.
  • &str: An immutable view into string data located on the heap, stack, or embedded in the read-only data segment of the binary (string literals).