Rust Strings Confused Me Until I Stopped Treating Them Like Any Other Type
In Python, a string is a string. In Java, a String is an object and a char[] is something you almost never use directly. Coming to Rust, the immediate question is why there are two string types, what the difference actually is, and why the compiler keeps rejecting code that looks like it should work.
Rust does not have a single string type. It has a small ecosystem of related types, each answering a different question about ownership, encoding, and where the data lives.
str and String
String is an owned, heap-allocated, growable sequence of UTF-8 bytes. When you own a String, you are responsible for its memory, and when it goes out of scope, that memory is freed. It is the string type you reach for when you need to build, modify, or store a string.
str is Rust’s dynamically sized UTF-8 string type. Because it has no compile-time size, you almost never work with str directly. Instead you use &str, a string slice that borrows a sequence of UTF-8 bytes stored elsewhere. A &str is a fat pointer, two words wide, carrying the address of the string data and its length.
fn main() {
let owned: String = String::from("hello");
let literal: &str = "hello"; // &'static str — lives in the binary
let borrowed: &str = &owned; // borrows from owned's heap allocation
}
fn main() {
let owned: String = String::from("hello");
let literal: &str = "hello"; // &'static str — lives in the binary
let borrowed: &str = &owned; // borrows from owned's heap allocation
}
The string literal "hello" has type &'static str. The 'static lifetime means the referenced string data lives for the entire duration of the program. On most platforms this data resides in the program’s read-only data section. When you borrow from a String, the resulting &str has a lifetime tied to that String, not 'static.
When you need to modify a String after creating it:
let mut s = String::from("Hello");
s.push(','); // appends a single char
s.push_str(" world"); // appends a &str
// s is now "Hello, world"
let mut s = String::from("Hello");
s.push(','); // appends a single char
s.push_str(" world"); // appends a &str
// s is now "Hello, world"
When you know the final size in advance, String::with_capacity avoids repeated reallocations:
let mut s = String::with_capacity(64);
s.push_str("hello");
s.push_str(", world"); // no reallocation if total length stays under 64
let mut s = String::with_capacity(64);
s.push_str("hello");
s.push_str(", world"); // no reallocation if total length stays under 64
The function signature question
If a function only needs to read a string, the idiomatic signature takes &str, not &String:
// idiomatic
fn print_greeting(name: &str) {
println!("Hello, {name}!");
}
// not idiomatic
fn print_greeting_worse(name: &String) {
println!("Hello, {name}!");
}
// idiomatic
fn print_greeting(name: &str) {
println!("Hello, {name}!");
}
// not idiomatic
fn print_greeting_worse(name: &String) {
println!("Hello, {name}!");
}
Taking &String is strictly less flexible. String implements Deref<Target = str>, so whenever a &str is expected the compiler coerces &String to &str automatically. A caller with a String can pass it to either function, but a caller with a &str can only pass it to the &str version. Taking &str accepts both with no extra work from the caller.
If a function needs to store or modify the string, take String. If it only needs to read it, take &str.
to_string, to_owned, and String::from
All three produce an owned String from a string literal and are all correct. The distinction is in what traits they express.
String::from("text") is the most explicit and most common in examples.
"text".to_owned() calls the ToOwned trait, which exists for borrowed data that has an owned counterpart. For string slices it produces a String.
"text".to_string() calls the ToString trait, automatically implemented for any type that implements Display. It works on non-slice types too, which makes it more general but identical to the others for string literals.
Pick one and be consistent within a codebase.
The + operator is ownership in disguise
let s1 = String::from("hello");
let s2 = String::from(", world");
let s3 = s1 + &s2; // s1 is moved here
// println!("{s1}"); // compile error: s1 was moved
let s1 = String::from("hello");
let s2 = String::from(", world");
let s3 = s1 + &s2; // s1 is moved here
// println!("{s1}"); // compile error: s1 was moved
The + operator is trait syntax. String implements Add<&str>:
<button data-code="impl Add for String {
type Output = String;
fn add(mut self, s: &str) -> String { … }
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
impl Add<&str> for String {
type Output = String;
fn add(mut self, s: &str) -> String { ... }
}
impl Add<&str> for String {
type Output = String;
fn add(mut self, s: &str) -> String { ... }
}
It takes ownership of the left-hand side and borrows the right-hand side. The &s2 in s1 + &s2 also goes through a Deref coercion from &String to &str automatically. After the operation, s1 has been moved into the result, avoiding an extra allocation by reusing s1‘s heap buffer when possible.
When you need to preserve ownership of both inputs, or concatenate more than two strings, use format!:
let s3 = format!("{s1}{s2}"); // s1 and s2 both still valid
let s3 = format!("{s1}{s2}"); // s1 and s2 both still valid
String slices and indexing
Rust strings cannot be indexed by integer position:
let s = String::from("hello");
let c = s[0]; // compile error
let s = String::from("hello");
let c = s[0]; // compile error
This is deliberate. Rust strings are UTF-8, and a single Unicode scalar value can occupy one to four bytes. Indexing by byte position without checking whether it falls on a character boundary would produce garbage or panic at runtime.
To borrow part of a string, take a slice using a byte range:
let s = String::from("hello");
let hello = &s[0..5]; // &str pointing into s
// panics at runtime if the range boundary splits a multibyte character
let s = String::from("hello");
let hello = &s[0..5]; // &str pointing into s
// panics at runtime if the range boundary splits a multibyte character
To iterate over Unicode scalar values, use .chars(). To iterate over raw bytes, use .bytes().
let s = "héllo";
for c in s.chars() {
print!("{c} ");
}
// h é l l o
// s.len() is 6 because é is two bytes
// s.chars().count() is 5
let s = "héllo";
for c in s.chars() {
print!("{c} ");
}
// h é l l o
// s.len() is 6 because é is two bytes
// s.chars().count() is 5
One precision worth keeping in mind: .chars() yields Unicode scalar values, not grapheme clusters. A user-perceived character like a flag emoji or a letter with a combining diacritic can be multiple scalar values. If you need to split or count by what a user would consider a visible character, the unicode-segmentation crate provides .graphemes(true) which handles this correctly.
Cow and conditional allocation
Cow<'_, str> is an enum that holds either a borrowed &str or an owned String:
<button data-code="// mental model only — not real Rust
enum StringCow {
Borrowed(&'a str),
Owned(String),
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// mental model only — not real Rust
enum StringCow<'a> {
Borrowed(&'a str),
Owned(String),
}
// mental model only — not real Rust
enum StringCow<'a> {
Borrowed(&'a str),
Owned(String),
}
It defers allocation until you actually need to modify the data:
Cow {
if input.chars().all(|c| c.is_lowercase()) {
Cow::Borrowed(input) // no allocation
} else {
Cow::Owned(input.to_lowercase()) // allocates only when necessary
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::borrow::Cow;
fn normalise(input: &str) -> Cow<str> {
if input.chars().all(|c| c.is_lowercase()) {
Cow::Borrowed(input) // no allocation
} else {
Cow::Owned(input.to_lowercase()) // allocates only when necessary
}
}
use std::borrow::Cow;
fn normalise(input: &str) -> Cow<str> {
if input.chars().all(|c| c.is_lowercase()) {
Cow::Borrowed(input) // no allocation
} else {
Cow::Owned(input.to_lowercase()) // allocates only when necessary
}
}
The caller gets back a value they can use as a &str in either case via Deref coercion. Most Rust programmers do not reach for it every day, but it shows up in parsers, HTTP libraries, and anywhere that processes strings that are usually valid but occasionally need transformation.
OsStr and Path
OsStr and its owned counterpart OsString exist because file paths and environment variables are not guaranteed to be valid UTF-8 on all platforms. Windows paths are represented using the platform’s native 16-bit encoding. Unix paths use arbitrary bytes. str and String cannot represent either accurately.
OsStr stores the platform’s native representation. Calling to_str() attempts to borrow it as UTF-8, returning Option<&str>. When you need a best-effort conversion, to_string_lossy() returns a Cow<str> that borrows the original if it is valid UTF-8 and substitutes replacement characters otherwise.
use std::path::Path;
let path = Path::new("/some/path/file.txt");
if let Some(ext) = path.extension() {
println!("{}", ext.to_string_lossy()); // "txt"
}
use std::path::Path;
let path = Path::new("/some/path/file.txt");
if let Some(ext) = path.extension() {
println!("{}", ext.to_string_lossy()); // "txt"
}
The practical summary
Use &str for function parameters that only read a string. Use String when you need ownership, storage, or modification, and String::with_capacity when you know the expected size. Use format! for concatenation involving more than two strings or when you need to preserve ownership. Use .chars() for Unicode scalar value iteration, and unicode-segmentation when you need grapheme clusters. Reach for Cow<str> when a function processes strings that are usually fine but occasionally need transformation. Use OsStr and Path for anything that touches the filesystem or environment variables.
Once you stop thinking of Rust as having “two string types” and instead see a small ecosystem of types representing ownership, borrowing, allocation, and platform encoding, the APIs stop feeling arbitrary. They are a direct expression of what your code is actually doing.
All code in this series targets Rust 2021 edition on stable.
All code in this series is compiled and tested in the companion repository: github.com/shan305/data-structures-rust-java
If you want the full implementation with explanations, five problems per chapter, and every data structure built in both Rust and Java side by side: Ownership vs. Reference: Data Structures and Algorithms in Rust and Java.
Free Preview Before you Buy
For the Rust foundations this series builds on: Zero to Rust: A Systems Programmer’s Field Guide — $7 · Free 20-page sample


