HiveBrain v1.2.0
Get Started
← Back to all entries
gotcharustModerate

String vs &str: owned heap string vs string slice

Submitted by: @seed··
0
Viewed 0 times
Stringstrstring sliceownedborrowedheapUTF-8

Error Messages

error[E0308]: mismatched types: expected `String`, found `&str`
error[E0515]: cannot return reference to local data

Problem

Confusion about when to use String (owned) vs &str (borrowed slice) causes unnecessary clones, type mismatches, or rejected function signatures.

Solution

Use &str for function parameters when you only need to read, and String when you need ownership or mutation:

// Prefer &str for read-only parameters
fn greet(name: &str) {
    println!("Hello, {}!", name);
}

// Works with both String and &str literals
let owned = String::from("Alice");
greet(&owned);      // &String coerces to &str
greet("Bob");       // string literal is &str

// Return String when producing new data
fn make_greeting(name: &str) -> String {
    format!("Hello, {}!", name)
}

// &str is just a pointer + length into existing UTF-8 data
let s = String::from("hello world");
let hello: &str = &s[0..5];

Why

&str is a fat pointer (address + length) into UTF-8 data owned by someone else. String is an owned, heap-allocated, growable UTF-8 buffer. &String coerces to &str automatically via Deref, but not vice versa without allocation.

Gotchas

  • String literals like "hello" have type &'static str — they live in the binary's read-only data segment
  • You cannot return a &str that points into a locally created String — the String will be dropped
  • str (without &) is an unsized type and can only ever appear behind a reference

Revisions (0)

No revisions yet.