🧩 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.

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

rust
Loading…

🧵 Slice Syntax Reference

Here's a quick guide to the different ways you can create slices:

Common Slice Patterns
SyntaxDescriptionExample
&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]
rust
Loading…

📚 Slices in Functions

One of the most common uses for slices is in function parameters:

rust
Loading…

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:

rust
Loading…

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:

rust
Loading…

The Relationship to References

String slices (&str) are just slices of String data - they're references to parts of strings:

rust
Loading…

✅ Recap

Mastering slices is essential for efficient Rust code. They're a perfect example of how Rust achieves both performance and safety by default! 🚀