Introduction
A slice lets you reference a contiguous portion of a collection - like an array, Vec, or String - rather than the whole thing. Slices don't own the data they point to; they are a kind of reference, so they follow the same borrowing rules as any other reference. This makes them a cheap, safe way to pass around 'a view into' data without copying it.
Cricket analogy: A slice is like a TV director cutting to a highlights reel of just overs 15-20 of an innings rather than replaying the whole match tape; it references that segment without copying the entire recording, and normal broadcast-rights rules still apply.
Syntax
let v = vec![10, 20, 30, 40, 50];
let slice: &[i32] = &v[1..3]; // elements at index 1 and 2
let s = String::from("hello world");
let word: &str = &s[0..5]; // string slice, "hello"Explanation
The general slice type &[T] refers to a run of elements inside an array or Vec<T>, using a half-open range where the start index is inclusive and the end index is exclusive. A string slice, &str, is a specialized slice type over UTF-8 bytes and is what you get from slicing a String or from a string literal. Because a slice is just a pointer plus a length, it borrows from the underlying data - the normal borrowing rules apply, so you cannot mutate the original collection while an immutable slice into it is still alive.
Cricket analogy: The &[T] slice using a half-open range is like specifying overs 10 to 15 where over 10 is bowled but over 15 hasn't started yet; and because it's just a reference into the scorecard, you can't rewrite earlier overs while that range is still being reviewed.
Example
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &b) in bytes.iter().enumerate() {
if b == b' ' {
return &s[0..i];
}
}
&s[..] // whole string if no space found
}
fn main() {
let sentence = String::from("hello world");
let word = first_word(&sentence);
println!("First word: {}", word);
let numbers = [1, 2, 3, 4, 5];
let middle = &numbers[1..4];
println!("Middle slice: {:?}", middle);
}Output
First word: hello
Middle slice: [2, 3, 4]Key Takeaways
- A slice, &[T], is a reference to a contiguous sequence within an array or Vec, without owning the data.
- &str is a string slice - a reference into UTF-8 encoded text, often a view into a String.
- Slice ranges are half-open: start..end includes start but excludes end.
- Slices borrow from their source, so normal borrowing rules apply (no mutation while a slice is alive).
- Function parameters typed &str can accept both string literals and slices of a String, making functions more flexible.
Practice what you learned
1. What does the slice &v[1..3] on a Vec<i32> named v refer to?
2. What is the type of a string slice in Rust?
3. Does a slice own the data it points to?
4. Why is it generally preferred to write a function parameter as &str instead of &String?
5. What must be true for a slice to remain valid?
Was this page helpful?
You May Also Like
The String Type in Rust
Rust's owned, growable, heap-allocated String type versus the borrowed &str string slice, and how to build and combine them.
Borrowing and References in Rust
How Rust lets code access data without taking ownership, using immutable and mutable references checked by the borrow checker.
Vectors in Rust
A Vec<T> is a growable, heap-allocated list that lets you store a variable number of values of the same type.
Tuples and Arrays in Rust
Tuples group a fixed set of differently-typed values together, while arrays hold a fixed-size list of same-typed values.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics