Skip to main content Slices | Rust Fundamentals lesson | BraveProgrammerSlices
Slices are views into a contiguous sequence without owning the data. They're references to a portion of a collection.
Array Slices
fn main() {
let arr = [1, 2, 3, 4, 5];
= &arr[..];
(\
let
slice
1
4
println!
"Slice: {:?}\", slice);
let all = &arr[..]; // Entire array
let first_two = &arr[..2]; //[1, 2]
let last_two = &arr[3..]; // [4, 5]
}
Slice syntax [start..end] excludes the end index (Pythonic style).
String Slices
String slices (&str) are views into a String:
fn main() {
let s = String::from(\"hello world\");
let hello = &s[0..5]; // \"hello\"
let world = &s[6..11]; // \"world\"
let entire = &s[..]; // Entire string
println!(\"First word: {}\", hello);
}
String literals (\"hello\") are &str types.
Practical: Finding the First Word
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
fn main() {
let s = String::from(\"hello world\");
let word = first_word(&s);
println!(\"First word: {}\", word); // \"hello\"
}
Important Type Insight
let s = String::from(\"hello\");
let slice: &str = &s[0..5]; // &str is a slice
let literal: &str = \"world\"; // Literal is also &str
Both are &str—Rust treats string literals as slices of static data.
Slice Benefits
- No copying: Views into existing data
- Type safety: Can't create invalid indices at compile time
- Ergonomic: Enables functions to accept both
String and &str
fn analyze(s: &str) {
println!(\"Length: {}\", s.len());
}
let my_string = String::from(\"hello\");
analyze(&my_string); // String reference (coerces to &str)
analyze(\"world\"); // String literal
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities