Rust Strings Explained: &str vs String, UTF-8 Indexing, and Conversions
Why s[0] does not compile, why slicing can panic, and when a &str becomes an owned String. The UTF-8 rules behind every Rust string error.

Quick Summary
Rust has exactly two string types in everyday use. &str is a borrowed, immutable view into UTF-8 bytes — a fat pointer carrying an address and a length. String is an owned, growable, UTF-8 buffer on the heap, effectively a Vec<u8> that maintains the invariant that its contents are valid UTF-8. Everything else (OsString, PathBuf, CString) exists because "text" and "bytes" are not the same thing at the operating system boundary.
Because both are UTF-8, indexing by integer does not exist. s[0] is a compile error, not a runtime surprise, and &s[0..2] panics at runtime if offset 2 is not a character boundary. That is not a limitation to work around — it is the type system refusing to let you produce invalid text. s.len() returns bytes; s.chars().count() returns characters and costs O(n).
The conversion rules are short: String derefs to str, so &String coerces to &str at call sites. to_string() and String::from both allocate a copy. &str never allocates. When a function only reads text, take &str; when it needs to store or return text, return String.
Basic Syntax & Signature
fn main() {
// Three ways to make the same content, different ownership.
let a: &str = "literal"; // 'static, in the binary
let b: String = String::from("literal"); // heap, owned
let c: String = "literal".to_owned(); // same as to_string()
// &String coerces to &str.
fn takes_str(s: &str) -> usize { s.len() }
assert_eq!(takes_str(&b), 7);
assert_eq!(takes_str(&c), 7);
// Growth: push_str for &str, push for one char.
let mut s = String::with_capacity(32);
s.push_str("hello");
s.push(' ');
s.push('world');
assert_eq!(s, "hello world");
// Concatenation: `+` consumes the left String and borrows the right.
let left = String::from("foo");
let joined = left + "bar"; // left is moved
assert_eq!(joined, "foobar");
// format! borrows everything and returns a new String.
let f = format!("{}-{}", joined, 42);
// Byte vs character length.
let emoji = "héllo🌍";
assert_eq!(emoji.len(), 10); // bytes
assert_eq!(emoji.chars().count(), 6); // characters
assert_eq!(emoji.chars().nth(1), Some('é'));
// Slicing only on char boundaries; get() is the checked version.
assert_eq!(&emoji[..1], "h");
assert_eq!(emoji.get(0..2), None); // 'é' is two bytes: 1..3 would be valid
assert_eq!(emoji.get(1..3), Some("é"));
// Iteration.
let bytes: usize = emoji.bytes().count();
let indices: Vec<(usize, char)> = emoji.char_indices().take(3).collect();
assert_eq!(bytes, 10);
assert_eq!(indices, vec![(0, 'h'), (1, 'é'), (3, 'l')]);
let upper: String = "abc".chars().map(|c| c.to_ascii_uppercase()).collect();
assert_eq!(upper, "ABC");
println!("{f}");
}Signatures that matter:
impl str {
pub fn len(&self) -> usize; // bytes
pub fn is_empty(&self) -> bool;
pub fn chars(&self) -> Chars<'_>; // scalar values
pub fn char_indices(&self) -> CharIndices<'_>;
pub fn bytes(&self) -> Bytes<'_>;
pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output>;
pub fn split(&self, pat: impl Pattern) -> Split<'_, impl Pattern>;
pub fn split_once(&self, pat: impl Pattern) -> Option<(&str, &str)>;
pub fn trim(&self) -> &str;
pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str>;
pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>;
}
impl String {
pub fn new() -> String;
pub fn with_capacity(capacity: usize) -> String;
pub fn push_str(&mut self, string: &str);
pub fn push(&mut self, ch: char);
pub fn insert_str(&mut self, idx: usize, string: &str); // panics off-boundary
pub fn replace_range<R: RangeBounds<usize>>(&mut self, range: R, replace_with: &str);
pub fn truncate(&mut self, new_len: usize); // panics off-boundary
pub fn into_bytes(self) -> Vec<u8>;
pub fn as_str(&self) -> &str;
}Key Comparison Table
| Aspect | &str | String |
|---|---|---|
| Ownership | Borrowed | Owned |
| Allocation | None (points into existing buffer) | Heap buffer |
| Size on stack | 16 bytes (ptr + len) | 24 bytes (ptr + len + cap) |
| Growable | No | Yes |
Deref to str | — | Yes (Deref<Target = str>) |
| Typical parameter | fn f(s: &str) | fn f(s: String) when taking ownership |
| Return from function | Borrowed from an input or 'static | Owned, no lifetime |
| Clone cost | Free (copy of pointer) | Allocates and copies bytes |
| Conversion | Cost | When |
|---|---|---|
&str -> String via to_string() / String::from | Allocates | Storing text in a struct |
String -> &str via &s or s.as_str() | Free | Passing to a reader |
String -> Vec<u8> via into_bytes() | Free | Binary protocols |
Vec<u8> -> String via String::from_utf8 | Validates O(n) | Untrusted input |
&[u8] -> &str via std::str::from_utf8 | Validates O(n) | Parsing network data |
String -> &'static str via Box::leak | Leaks | Config that lives forever, rarely |
&str -> Cow<str> | Conditional | Return either borrowed or owned |
Practical Edge Cases & Deep Dives
1. UTF-8 boundaries: the panic everyone hits once
fn main() {
let s = "naïve café";
// 'ï' is two bytes at index 2..4, so byte 3 is inside a character.
let result = std::panic::catch_unwind(|| &s[0..3]);
assert!(result.is_err());
// Checked slicing returns None instead of panicking.
assert_eq!(s.get(0..3), None);
assert_eq!(s.get(0..2), Some("na"));
// Cutting a prefix safely.
let mut cut = s.to_string();
if cut.is_char_boundary(3) {
cut.truncate(3);
} else {
// Find the nearest boundary we can use.
let boundary = (0..=3).rev().find(|i| cut.is_char_boundary(*i)).unwrap();
cut.truncate(boundary);
}
assert_eq!(cut, "na");
// Correct prefix removal without arithmetic on byte offsets.
let rest = s.strip_prefix("naï").unwrap_or(s);
assert_eq!(rest, "ve café");
}str::is_char_boundary is the primitive to reach for whenever byte arithmetic is unavoidable. Truncating a user-supplied string at a byte offset is a production panic waiting to happen — and it is common in code that copies s[..200] to build a preview.
2. split patterns and the empty-string trap
fn main() {
let csv = "a,b,,d";
let fields: Vec<&str> = csv.split(',').collect();
assert_eq!(fields, ["a", "b", "", "d"]); // empty field preserved
assert_eq!(csv.split(',').count(), 4);
// Trailing separator produces a trailing empty field.
assert_eq!("a,".split(',').collect::<Vec<_>>(), ["a", ""]);
// An empty string splits into one empty piece, not zero.
assert_eq!("".split(',').collect::<Vec<_>>(), [""]);
assert_eq!("".split_whitespace().count(), 0); // whitespace differs
// splitn limits the pieces; the last piece keeps the remainder intact.
let kv = "key=value=with=equals";
let parts: Vec<&str> = kv.splitn(2, '=').collect();
assert_eq!(parts, ["key", "value=with=equals"]);
// split_once is the two-part version returning Option.
assert_eq!("user:pass".split_once(':'), Some(("user", "pass")));
assert_eq!("nocolon".split_once(':'), None);
// Multi-pattern splitting uses closures or &[char].
let cleaned: Vec<&str> = "a, b; c".split(|c: char| c == ',' || c == ';')
.map(str::trim)
.filter(|s| !s.is_empty())
.collect();
assert_eq!(cleaned, ["a", "b", "c"]);
}str::split accepts a Pattern, which means char, &str, &[char], or a FnMut(char) -> bool. The same Pattern machinery powers replace, trim_matches, starts_with, and find, so learning it once covers a dozen methods.
3. Parsing, formatting, and the Display/FromStr pair
use std::fmt;
use std::str::FromStr;
#[derive(Debug, PartialEq)]
struct Port(u16);
impl FromStr for Port {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let n: u16 = s.trim().parse().map_err(|_| format!("not a port: {s}"))?;
if n == 0 { return Err("port 0 is reserved".into()); }
Ok(Port(n))
}
}
impl fmt::Display for Port {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
fn main() {
assert_eq!("8080".parse::<Port>(), Ok(Port(8080)));
assert!("0".parse::<Port>().is_err());
assert_eq!(format!("{}", Port(443)), "443");
// Numbers: parse returns Result, never panics.
assert_eq!("0xff".parse::<u8>().is_err(), true); // no 0x prefix support
assert_eq!("255".parse::<u8>(), Ok(255));
assert_eq!(" 42 ".trim().parse::<i32>(), Ok(42));
// Float formatting: explicit precision avoids surprising output.
assert_eq!(format!("{:.2}", 2.0_f64), "2.00");
}parse is generic over FromStr, so "1,2,3".split(',').map(str::parse::<i32>) yields an iterator of Result<i32, _> — collecting into Result<Vec<i32>, _> short-circuits on the first failure, which is usually the behaviour you want for configuration input.
4. String in collections, and the Borrow shortcut
use std::collections::HashMap;
fn main() {
let mut ages: HashMap<String, u32> = HashMap::new();
ages.insert("ada".to_string(), 36);
ages.insert("grace".to_string(), 45);
// HashMap<String, V> can be queried with &str because String: Borrow<str>.
assert_eq!(ages.get("ada"), Some(&36));
assert_eq!(ages.get(&"ada".to_string()), Some(&36));
// But insert always allocates a new key unless the entry exists.
// entry + or_insert takes the String once; get does not.
ages.entry("alan".to_string()).or_insert(41);
// Building a comma-separated list without intermediate Vec.
let names: String = ages.keys().map(String::as_str).collect::<Vec<_>>().join(", ");
println!("{names}");
// Owned string slices of a String cannot outlive it.
let owner = String::from("temporary");
let slice: &str = &owner;
assert_eq!(slice.len(), 9);
// drop(owner); // compile error if `slice` were used afterwards
}Borrow<str> is why HashMap<String, T>::get("literal") works without allocating. It is also the reason the E0277: the trait bound 'String: Borrow<Q>' error appears when someone tries get(&5) on a HashMap<i32, T> with a mismatched type — the query type must hash identically to the stored key.
5. Bytes, files, and the non-UTF-8 boundary
use std::ffi::{OsStr, OsString};
use std::path::Path;
fn main() {
// Untrusted bytes: validate once, then treat as text.
let raw: Vec<u8> = vec![0x68, 0x69, 0xFF];
assert!(std::str::from_utf8(&raw).is_err());
assert_eq!(String::from_utf8_lossy(&raw), "hi\u{FFFD}");
// Owned round trip through bytes.
let s = String::from("data");
let bytes = s.into_bytes();
assert_eq!(String::from_utf8(bytes).unwrap(), "data");
// Paths are OS strings, not UTF-8 strings, on Unix and Windows alike.
let p = Path::new("/tmp/report.csv");
assert_eq!(p.extension(), Some(OsStr::new("csv")));
let mut name = OsString::from("report");
name.push(".csv");
assert_eq!(name, OsString::from("report.csv"));
// name.to_str() returns Option<&str>; it is None for invalid UTF-8.
assert_eq!(name.to_str(), Some("report.csv"));
}Converting Path to &str with to_str().unwrap() is a real crash on Linux and macOS for filenames containing arbitrary bytes. Keep paths as PathBuf, and only convert at the point where a human-readable message is produced.
6. Cow<str> for "borrow when you can, allocate when you must"
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input)
}
}
fn main() {
let borrowed = normalize("already_clean");
let owned = normalize("needs fixing");
assert!(matches!(borrowed, Cow::Borrowed(_)));
assert!(matches!(owned, Cow::Owned(_)));
assert_eq!(&*owned, "needs_fixing");
assert_eq!(borrowed.as_ref(), "already_clean");
}Cow<'a, str> is the standard return type for a function that transforms text only sometimes. It avoids an allocation on the common path without forcing every caller to handle two types, and it derefs to str, so it can be passed anywhere &str is expected.
Common Compilation/Runtime Mistakes
| Error / symptom | Cause | Fix |
|---|---|---|
E0277: the type 'str' cannot be indexed by 'usize' | s[0] on a &str or String | s.as_bytes()[0] or s.chars().nth(0) |
panicked: byte index 3 is not a char boundary | Slicing or truncating at a non-boundary | get, is_char_boundary, chars() |
E0308: expected '&str', found '&String' | Missing deref coercion at a generic boundary | &s or s.as_str() |
E0382: use of moved value after + | String + &str consumes the left operand | format! or push_str on a clone |
E0277: 'String: Borrow<&str>' in map.get | Query type mismatch | Pass &str, not &&str |
len() returns more than expected | Byte length, not character count | chars().count() |
truncate panics on user text | Byte offset inside a multibyte character | Round down to is_char_boundary |
to_uppercase changes length | Unicode case mapping expands (ß -> SS) | Accept it, or use ASCII-only paths for identifiers |
parse failing on valid-looking input | Leading/trailing whitespace | trim() before parse |
from_utf8 returns Err on file data | File is not UTF-8 (Latin-1, binary) | from_utf8_lossy or encoding_rs |
The one case that catches experienced developers: s.chars().count() inside a loop over a long string is O(n) each time, making the outer loop O(n²). If character counts are needed repeatedly, compute once and store the number, or keep byte offsets and convert to character positions only at the display layer.
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.