🧩 Slices in Rust Beginner Friendly
Slices let you reference a portion of a collection without taking ownership. They're one of Rust's most powerful features that helps write efficient, safe code.
- They allow you to work with just part of a collection
- They prevent unnecessary data copying
- They enforce memory safety at compile time
What is a Slice?
A slice is a reference to a contiguous sequence of elements in a collection. Think of it like saying:
"I want to look at this part of the data, not take the whole thing."
In Rust, slices are written as &[T]
for arrays/vectors and &str
for strings.
📏 Slicing an Array
🧵 Slice Syntax Reference
Here's a quick guide to the different ways you can create slices:
Syntax | Description | Example |
---|---|---|
&arr[a..b] | Elements from index a to b-1 | &nums[1..4] gives [20, 30, 40] |
&arr[..b] | Elements from start to b-1 | &nums[..2] gives [10, 20] |
&arr[a..] | Elements from a to the end | &nums[3..] gives [40, 50] |
&arr[..] | The entire collection | &nums[..] gives [10, 20, 30, 40, 50] |
📚 Slices in Functions
One of the most common uses for slices is in function parameters:
This pattern allows functions to work with any part of an array or vector without knowing its size in advance!
🔐 Safety First: Slice Bounds
Rust prevents you from accessing elements outside a collection's bounds:
This runtime check helps catch bugs early rather than causing undefined behavior.
📜 String Slices
String slices (&str
) are special because strings in Rust are UTF-8 encoded:
Always be careful when slicing strings containing non-ASCII characters. Slicing must occur on valid UTF-8 character boundaries or your program will panic!
The Relationship to References
String slices (&str
) are just slices of String
data - they're references to parts of strings:
✅ Recap
- Slices let you borrow parts of collections without taking ownership
- They're always references (
&
) - Common forms:
&[T]
for arrays/vectors and&str
for strings - They make functions more flexible by working with parts of collections
- They enforce bounds checking to prevent memory errors
Mastering slices is essential for efficient Rust code. They're a perfect example of how Rust achieves both performance and safety by default! 🚀