← Back to Rust Course | Chapter 9: Collections | Lesson 2 of 6

String vs str

String is your own growable notebook of text, while &str is just a quick peek at text someone else owns.

Creating a String

String::from() or .to_string() creates an owned, growable string on the heap that you can modify and that will be cleaned up automatically when it goes out of scope.

Example: Creating a String

markup
fn main() {
    let owned = String::from("Hello");
    println!("{}", owned);
}

Growing a String

Because String owns its data, it can grow by appending more text with methods like .push_str(), something a plain &str cannot do.

Example: Growing a String

markup
fn main() {
    let mut message = String::from("Hello");
    message.push_str(", Rust!");
    println!("{}", message);
}

Converting Between String and &str

You can borrow a String as a &str with &owned (or .as_str()), and convert a &str into an owned String with .to_string() or String::from().

Example: Converting Between String and &str

markup
fn main() {
    let owned: String = String::from("borrowed view");
    let borrowed: &str = &owned;
    println!("{}", borrowed);
    let back_to_owned: String = borrowed.to_string();
    println!("{}", back_to_owned);
}

Choosing Function Parameter Types

Accepting &str in a function lets it work with both string literals and borrowed String values, making it more flexible than requiring an owned String parameter.

Example: Choosing Function Parameter Types

markup
fn shout(text: &str) -> String {
    format!("{}!!!", text.to_uppercase())
}

fn main() {
    let owned = String::from("hello");
    println!("{}", shout(&owned));
    println!("{}", shout("literal"));
}
Common Mistakes
  1. Trying to use += to grow a &str directly -- only an owned, mutable String can be appended to.
  2. Forgetting that String::from() allocates on the heap, while a &str literal is embedded directly in the binary.
  3. Using String as a function parameter type when &str would accept both owned strings and literals more flexibly.
Chapter Summary
  • String is an owned, growable, heap-allocated text buffer.
  • &str is a borrowed, immutable view into string data, either from a String or a literal.
  • .to_string() or String::from() converts a &str into an owned String.
  • Prefer &str for function parameters that only need to read text, and String when you need to own or grow the text.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.