Rust Easy technical 1 views 1 min read

What is the difference between String and &str in Rust?

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Rust conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

String is an owned, growable, heap-allocated UTF-8 string (essentially a Vec<u8>) that you can mutate and extend. &str is a borrowed string slice: a pointer plus a length into UTF-8 data that may live in the binary, on the stack, or inside a String. It is immutable.

let owned: String = String::from("hi");
let slice: &str = &owned;       // borrow
let literal: &str = "static";   // &'static str

fn greet(name: &str) {
    println!("{name}");
}
greet(&owned);                  // deref coercion String -> &str

Prefer &str for function parameters because it accepts both String (through deref coercion) and string literals, making the API more flexible. Use String when the function must own or modify the data. Concatenation with + consumes the left-hand String, and format! is often clearer. &String can be coerced to &str, but &str cannot become &String, which is why libraries expose slices.

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?