Advanced 16 min readModule: Module 5: Slices & Memory Layout
Slices (&str, &[T]) & Memory Safety
Reference contiguous sub-sequences of collections with zero memory allocation using string and array slices.
What You Will Learn in This Lesson
- What a slice is: a pointer to starting element + length
- String slices (&str) vs heap-allocated String
- Array slices (&[i32]) for generic contiguous sub-views
Introduction & Core Concept
A slice is a reference to a contiguous sequence of elements in a collection rather than the whole collection.
WHY DOES THIS MATTER IN THE REAL WORLD?
String slices (&str) allow functions to accept both String and literal strings without performing heap allocations.
First Word Extractor with String Slice
rustrust
1234567891011121314fn 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 greeting = "Hello World";println!("First word: {}", first_word(greeting));}
Line-by-Line Technical Breakdown
1Slices prevent index-out-of-sync bugs because the borrow checker links the slice lifetime to the underlying data.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[RUST]
RUST SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Always use &str for function input arguments instead of &String.
Lesson Summary & Core Takeaways
- Slices provide zero-cost views into contiguous memory segments.