String vs &str Slices

🦀 Rust Lesson 9 Intermediate

Rust has two main string types: the heap-allocated growable String class, and the read-only string slice &str.

1 String (Heap) vs &str (Reference View)

Understanding Rust string differences is essential:

  • String: A heap-allocated, growable, UTF-8 encoded string. It owns its data. Created using `String::from()` or `.to_string()`.
  • &str: A lightweight, read-only slice reference pointing to a string sequence (either in heap, stack, or binary literal data). Does not allocate copy memory.
2 String Processing Code

Let's run a program illustrating string manipulations and slice conversions:

Rust — Strings ▶ Run Code
fn print_view(slice: &str) {
    println!("Viewing slice: {}", slice);
}

fn main() {
    // String literal slice (&str)
    let s1: &str = "hello";

    // Heap allocated String
    let mut s2: String = String::from("hello");
    s2.push_str(", world!"); // Modify heap data

    println!("s1 slice: {}", s1);
    println!("s2 growable: {}", s2);

    // Pass string reference view without copying
    print_view(&s2);
}
3 Code Challenge
Challenge: Write a program that slices a heap-allocated `String` using ranges (e.g. `&s[0..5]`). Pass the slice to a function accepting `&str` and print the slice.