Ownership & Borrowing · 9 min read · Intermediate
Slices (&str, &[T]) & String vs &str
Write flexible zero-copy APIs using string slices (&str) and array/vector slices (&[T]).
What you'll learn
- Choose &str for function parameters instead of &String
- Borrow contiguous sub-ranges with &[T] slices
- Understand why Rust strings are valid UTF-8 and cannot be indexed by byte directly
Overview
Write flexible zero-copy APIs using string slices (&str) and array/vector slices (&[T]).
Code Example
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
println!("{}", first_word("fearless concurrency"));
}
Key Takeaways
- Choose &str for function parameters instead of &String
- Borrow contiguous sub-ranges with &[T] slices
- Understand why Rust strings are valid UTF-8 and cannot be indexed by byte directly
Quick Check
Check Your Understanding
Score: 0 / 1
1. Why should Rust functions usually accept `s: &str` instead of `s: &String`?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.