str vs String in Rust
From the Rust cheat sheet · Strings · verified Jul 2026
&str vs String
The two string types, when to use each, and how to convert between them.
rust
// &str — string slice (borrowed, immutable, stack)
let greeting: &str = "hello";
// String — owned, growable, heap-allocated
let mut s = String::from("hello");
s.push_str(", world!");
s.push('!');
// Conversions
let owned: String = "hello".to_string();
let slice: &str = &owned;💡 Use &str for function parameters — it accepts both &str and &String (via deref coercion)
⚡ format!() creates a new String — like println! but returns instead of printing
📌 .len() returns bytes, not characters — use .chars().count() for Unicode char count
🟢 Rule of thumb: accept &str, return String — gives callers maximum flexibility
stringsstrstringconversions