0PricingLogin
Learn Rust Coding · Lesson

String vs &str

Ownership of text.

Owned vs Borrowed Text

Rust separates text ownership into two types:

  • Stringowns its data on the heap.
  • &strborrows a view of text it does not own.
fn main() {
    let owned = String::from("I own this");
    let borrowed: &str = "I am borrowed";
    println!("{} / {}", owned, borrowed);
}

Where the Data Lives

A String stores its bytes on the heap and can grow. A string literal &str is baked into the program binary and is fixed.

fn main() {
    let mut heap = String::from("grows");
    heap.push_str(" bigger");
    let fixed = "never changes";
    println!("{} | {}", heap, fixed);
}

All lessons in this course

  1. String vs &str
  2. Slices
  3. String Methods
  4. UTF-8 and Chars
← Back to Learn Rust Coding