Skip to the content.

string slice vs string literal

In Rust, a string literal and a string slice are closely related but not exactly the same. Here’s the distinction:

String Literal (&str)

String Slice (&str)

Key Differences

Aspect String Literal (&'static str) String Slice (&str)
Storage Stored in the program’s binary (static). Can borrow from literals or heap.
Lifetime Always 'static. Inherits the lifetime of the borrowed string.
Mutability Immutable by definition. Immutable because it’s a borrowed reference.
Size Fixed at compile time. Depends on what it borrows from.

Example

let literal: &'static str = "hello"; // A string literal
let s = String::from("world");
let slice: &str = &s; // A string slice borrowing from a `String`

println!("{literal}, {slice}");

In summary, a string literal is a specific type of string slice with a 'static lifetime and is hardcoded into the program, while a string slice can be a reference to any part of a string, regardless of whether it’s a literal or a heap-allocated String.