String vs &str (Rust)
String is an owned, growable, heap-allocated UTF-8 string; &str is a borrowed, fixed view into string data. The two work together: String owns the buffer, &str references part of it.
Rust
String is the owned type you build and mutate (push_str, push, format!); it owns its heap buffer. &str (a 'string slice') is a borrowed, read-only view — a pointer and length into existing UTF-8 data, often a string literal stored in the binary.
Best practice: take &str as function parameters and return String when you produce new owned text. Because String derefs to &str, you can pass &my_string anywhere a &str is wanted, so accepting &str makes a function maximally flexible.
Both are guaranteed valid UTF-8, so you can't index by byte position arbitrarily — you slice on character boundaries or iterate with .chars(). Convert with String::from(s) / s.to_string() to own, and &my_string[..] or .as_str() to borrow.
Syntax
let owned: String = String::from("hi");
let view: &str = &owned;Examples
Rust
fn shout(s: &str) -> String { s.to_uppercase() }
fn main() {
let name = String::from("rust");
println!("{}", shout(&name)); // String coerces to &str
println!("{}", shout("go")); // literal is &str
}Output:
RUST
GO