RRust By Example

String and &str

Difference between String and string slices (&str).

String and &str

Difference between String and string slices (&str).

Difficulty

Beginner

Code

rust
fn greet(name: &str) {
    println!("Hello, {}!", name);
}

fn main() {
    let s1: &str = "string literal";
    let s2: String = String::from("owned string");
    let s3: &str = &s2[..6];

    greet(s1);
    greet(&s2);
    println!("slice: {}", s3);
}

Explanation

&str is a string slice (reference). String is owned and growable.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the compound-types category to build a complete understanding of this topic.

More Compound Types Examples