The Analogy: The Bracket in the Margin
A long report sits on your desk and a colleague asks about "the bit on Q3 revenue". You do not photocopy those pages. You draw a bracket in the margin -- starts here, runs this far -- and hand them the report, open, with the bracket showing. Two pencil strokes, and they are looking at exactly the passage you meant.
Notice what the bracket actually is: a start and a length. Nothing else. It weighs the same whether it covers three lines or three hundred pages, and drawing it took the same two seconds either way. And it is emphatically not the text. It is a mark that points at text living somewhere else, in a document that belongs to someone else.
Two consequences follow immediately, and they are not optional. The report has to stay on the desk -- shred it and the bracket refers to nothing, while still looking like a perfectly good bracket. And the bracket has to fall on pages that exist. A bracket from page 400 to page 500 of a three-hundred-page report is not a smaller bracket. It is nonsense, and the person who tries to read it aloud is the one who finds that out.
Rust's slices are that bracket, implemented exactly: &[T] and &str are a start pointer plus a length, sixteen bytes on a sixty-four-bit machine rather than the eight a plain pointer takes. They borrow, so the owner has to outlive them, and the compiler enforces that for you. But the range itself is checked at run time, because a length is data and the compiler usually cannot know it -- so an out-of-bounds slice is a panic, not a build error. That is the one place in this module where the guarantee moves from compile time to run time, and it is worth knowing precisely where the line falls.
Syntax or Core Structure
A slice is written as a range index behind a &. The four range forms cover everything, and mutable slices let you edit the elements in place without owning them.
fn main() {
let nums = [10, 20, 30, 40, 50];
// A slice is a borrowed view: start plus length, nothing copied.
let all = &nums[..];
let middle = &nums[1..4];
let head = &nums[..2];
let tail = &nums[3..];
println!("all = {all:?}");
println!("middle = {middle:?}");
println!("head = {head:?}");
println!("tail = {tail:?}");
println!("len = {}, first = {:?}", middle.len(), middle.first());
// String slices work the same way, but the indices count bytes.
let text = String::from("hello world");
let hello = &text[..5];
let world = &text[6..];
println!("hello = {hello:?}, world = {world:?}");
// &String coerces to &str, so a function only needs to take &str.
println!("first word = {:?}", first_word(&text));
// A mutable slice can change the elements it points at.
let mut grades = [70, 55, 92, 48];
bump(&mut grades[1..3]);
println!("grades = {grades:?}");
// A slice carries its own length; there is no count to pass alongside.
println!("sum = {}", total(&grades));
println!("sum of tail = {}", total(&grades[2..]));
}
fn first_word(s: &str) -> &str {
match s.find(' ') {
Some(i) => &s[..i],
None => s,
}
}
fn bump(xs: &mut [i32]) {
for x in xs {
*x += 5;
}
}
fn total(xs: &[i32]) -> i32 {
xs.iter().sum()
}
Output:
all = [10, 20, 30, 40, 50]
middle = [20, 30, 40]
head = [10, 20]
tail = [40, 50]
len = 3, first = Some(20)
hello = "hello", world = "world"
first word = "hello"
grades = [70, 60, 97, 48]
sum = 275
sum of tail = 145
Three details in that program are easy to skim past. total(&grades) passes a &[i32; 4] where a &[i32] is wanted -- the compiler inserts an unsized coercion that throws away the compile-time length and records it as data instead. bump(&mut grades[1..3]) mutates elements 1 and 2 of grades itself, not a copy, which is why grades prints as [70, 60, 97, 48] afterwards. And first_word returns a &str with no lifetime annotation because elision ties the one output reference to the one input reference.
Now the part that is a run-time check rather than a compile-time one:
fn main() {
let nums = [1, 2, 3];
let bad = &nums[1..5];
println!("{bad:?}");
}
Output:
thread 'main' panicked at src/main.rs:3:16:
range end index 5 out of range for slice of length 3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
That compiles cleanly. The array's length is known here, but slice indexing goes through the same Index implementation that a runtime-sized Vec uses, so the bound is verified when the line runs. Every slice index in Rust is bounds-checked -- you cannot read past the end -- but "checked" means "panics", not "refuses to build".
Technical Depth: What a Slice Actually Is
A slice reference is two words, not one
A &T for an ordinary type is one machine word: an address. A &[T] is two: the address of the first element and the number of elements. That second word is why a slice can be handed around without the length travelling separately in another parameter, and it is what people mean by a "fat pointer".
use std::mem::size_of;
fn main() {
println!("&i32 = {}", size_of::<&i32>());
println!("&[i32] = {}", size_of::<&[i32]>());
println!("&str = {}", size_of::<&str>());
println!("&[i32; 5] = {}", size_of::<&[i32; 5]>());
println!("Box<[i32]> = {}", size_of::<Box<[i32]>>());
}
Output (on a 64-bit target):
&i32 = 8
&[i32] = 16
&str = 16
&[i32; 5] = 8
Box<[i32]> = 16
The interesting row is &[i32; 5], which is eight bytes. An array's length lives in its type, so a reference to one needs no length word. The moment you coerce it to &[i32] the length moves out of the type and into the pointer, and the pointer doubles in size. Box<[i32]> is fat for the same reason: the thing it owns is unsized.
The sized and unsized families
[T] and str are types you can name but never hold directly, because their size is not known at compile time. They only ever exist behind some pointer.
| Type | Owns the data | Known size | Notes |
|---|---|---|---|
[T; N] | yes | yes | length is part of the type |
[T] | -- | no | can only exist behind a pointer |
&[T] | no | yes | shared slice, two words |
&mut [T] | no | yes | exclusive slice, two words |
Vec<T> | yes | yes | growable; derefs to [T] |
Box<[T]> | yes | yes | fixed length on the heap, no spare capacity |
str | -- | no | UTF-8 bytes, unsized |
&str | no | yes | string slice, two words |
String | yes | yes | growable UTF-8; derefs to str |
Because Vec<T> derefs to [T] and String derefs to str, every slice method is available on the owned type too. v.len(), v.iter(), v.sort() and v.windows(2) are all slice methods reached through Vec's Deref.
The range forms, including the empty ones
| Written | Covers |
|---|---|
&v[..] | every element |
&v[a..b] | index a up to but not including b |
&v[a..=b] | index a through b inclusive |
&v[a..] | index a to the end |
&v[..b] | the start up to but not including b |
Empty slices are ordinary values, not errors. For a five-element v, both &v[2..2] and &v[5..] are legal and yield a slice of length zero; &v[6..] panics. The rule is that the endpoints must satisfy start <= end <= len, so touching len exactly is always fine.
Indexing panics; get returns an Option
For every panicking form there is a non-panicking one, and get accepts a range as happily as it accepts a single index.
| Expression | Out of range behaviour |
|---|---|
&v[1..5] | panics |
v.get(1..5) | None |
v[9] | panics |
v.get(9) | None |
v.first(), v.last() | None when empty |
v.split_at(mid) | panics if mid > len |
v.split_at_checked(mid) | None if mid > len (Rust 1.80+) |
Use the indexing form when an out-of-range value would be a bug in your own code and you want it to fail loudly. Use get when the index came from outside -- a config file, a request, a parsed integer -- because then out-of-range is a case to handle, not a defect.
Views, overlapping and otherwise
fn main() {
let data = [3, 1, 4, 1, 5, 9, 2, 6];
// Non-panicking access, including with a range.
println!("get(2..5) = {:?}", data.get(2..5));
println!("get(2..99) = {:?}", data.get(2..99));
println!("get(99) = {:?}", data.get(99));
println!("empty = {:?}", &data[3..3]);
// Overlapping views, for comparing neighbours.
let rising = data.windows(2).filter(|w| w[1] > w[0]).count();
println!("rising pairs = {rising}");
// Non-overlapping views, for batching.
for (i, chunk) in data.chunks(3).enumerate() {
println!("chunk {i} = {chunk:?} (len {})", chunk.len());
}
// Two disjoint mutable halves of one array, at the same time.
let mut copy = data;
let (left, right) = copy.split_at_mut(4);
left.sort_unstable();
right.reverse();
println!("left = {left:?}");
println!("right = {right:?}");
println!("whole = {copy:?}");
}
Output:
get(2..5) = Some([4, 1, 5])
get(2..99) = None
get(99) = None
empty = []
rising pairs = 4
chunk 0 = [3, 1, 4] (len 3)
chunk 1 = [1, 5, 9] (len 3)
chunk 2 = [2, 6] (len 2)
left = [1, 1, 3, 4]
right = [6, 2, 9, 5]
whole = [1, 1, 3, 4, 6, 2, 9, 5]
windows(2) yields overlapping pairs, so an eight-element array gives seven windows; chunks(3) yields disjoint groups and the last one is short rather than padded or dropped. Both panic if you ask for size zero.
split_at_mut is the escape hatch for the rule you met in the previous lesson. Two &mut borrows of the same array cannot coexist, and yet left and right are exactly that -- because the function's signature promises the compiler that the two halves are disjoint. Inside the standard library it is implemented with unsafe code, since the borrow checker has no way to verify a claim about arithmetic. The last println! reads copy again, which is fine: by non-lexical lifetimes both mutable borrows are dead after their final use two lines earlier.
String slices count bytes, and the bytes have to line up
A &str is a slice of UTF-8 bytes. len() reports bytes, ranges are byte offsets, and a range endpoint that falls in the middle of a multi-byte character is rejected -- at run time, like any other slice bound.
fn main() {
// "cafe" with an acute accent: five bytes, four characters.
let s = String::from_utf8(vec![b'c', b'a', b'f', 0xC3, 0xA9]).unwrap();
println!("bytes = {}, chars = {}", s.len(), s.chars().count());
println!("is_char_boundary(4) = {}", s.is_char_boundary(4));
println!("get(..4) = {:?}", s.get(..4));
println!("get(..3) = {:?}", s.get(..3));
let _bad = &s[..4];
}
Output (stdout and stderr shown together):
bytes = 5, chars = 4
is_char_boundary(4) = false
get(..4) = None
get(..3) = Some("caf")
thread 'main' panicked at src/main.rs:8:17:
byte index 4 is not a char boundary; ...
The real message continues by naming the character byte 4 landed inside and giving its byte range; it is cut short here only because this page is ASCII-only. The accented character occupies bytes 3 and 4, so ..3 and ..5 are both valid and ..4 is not.
This is why str deliberately does not implement Index<usize>. Writing s[0] gives you a compile error, not a byte:
error[E0277]: the type `str` cannot be indexed by `{integer}`
The design forces you to say which unit you meant. s.as_bytes()[0] if you want a byte, s.chars().next() if you want a character, s.char_indices() if you want both a character and the byte offset where it starts.
| Want | Use |
|---|---|
| byte count | s.len() |
| character count | s.chars().count() |
| the raw bytes as a slice | s.as_bytes() |
| characters | s.chars() |
| characters with byte offsets | s.char_indices() |
| a substring that might not line up | s.get(a..b) |
| check an offset before slicing | s.is_char_boundary(i) |
For text that is known to be ASCII -- log levels, hex digits, protocol keywords -- byte offsets and character offsets coincide and none of this bites. It matters the moment real user text arrives.
Real World Example: Parsing a Log Line Without Allocating
Log parsing is where slices pay for themselves. Each line has a timestamp, a level, a target and a message, and every one of those fields is already sitting in the buffer -- so a parser that returns Strings is copying data that has not moved and will not move.
/// Splits a log line into (timestamp, level, target, message).
/// Every field returned is a slice of `line`; nothing is copied.
fn parse(line: &str) -> Option<(&str, &str, &str, &str)> {
let mut rest = line.trim();
let mut fields = [""; 3];
for slot in fields.iter_mut() {
let end = rest.find(' ')?;
*slot = &rest[..end];
rest = rest[end..].trim_start();
}
let level = fields[1];
if !matches!(level, "TRACE" | "DEBUG" | "INFO" | "WARN" | "ERROR") {
return None;
}
if rest.is_empty() {
return None;
}
Some((fields[0], level, fields[2], rest))
}
fn main() {
let log = [
"2026-09-03T12:00:01Z INFO api::routes request accepted",
"2026-09-03T12:00:02Z WARN api::db slow query: 1400ms",
"malformed line with no level",
"2026-09-03T12:00:04Z ERROR api::auth token expired",
"just two words",
];
let mut kept = 0;
let mut skipped = 0;
for line in log {
match parse(line) {
Some((ts, level, target, message)) => {
kept += 1;
println!("{level:<5} {target:<12} {message}");
if level == "ERROR" {
println!(" at {ts}");
}
}
None => {
skipped += 1;
println!("skip: {line:?}");
}
}
}
println!();
println!("kept {kept}, skipped {skipped}");
}
Output:
INFO api::routes request accepted
WARN api::db slow query: 1400ms
skip: "malformed line with no level"
ERROR api::auth token expired
at 2026-09-03T12:00:04Z
skip: "just two words"
kept 3, skipped 2
Nothing in parse allocates. Each of the four returned fields is a start pointer and a length aimed into the original line, which means the cost of parsing is independent of how long the fields are. Run this over a fifty-megabyte log and the parser's allocation count stays at zero; the version that returns owned Strings would allocate four times per line, so two hundred thousand lines is eight hundred thousand allocations bought for nothing.
The subtle part is the loop. rest is reassigned on every pass, and yet the slices already stored in fields stay valid. That works because reborrowing through a shared reference hands back the original lifetime: &rest[..end] borrows the data line points at, not the local variable rest. Moving rest forward is just overwriting two machine words. Had rest been a String that the loop consumed from the front, every stored field would have been left dangling and the compiler would have said so.
No lifetime annotations appear anywhere, because elision covers this shape exactly: one input reference means every output reference borrows from it. The compiler therefore already knows the returned tuple must not outlive line, and it will reject any attempt to stash a parsed field somewhere that outlives the buffer. A production parser would return a named struct instead of a four-tuple, which does require writing the lifetime out as Entry<'a> -- Module 6 covers that syntax -- but the guarantee being enforced is the same one.
Validation is what earns the Option. The ? on find handles "this line does not have enough fields", and matches! handles "the second field is not a log level"; both return None rather than a confidently wrong answer, which is why "malformed line with no level" is rejected even though it splits into four pieces perfectly well. Note what did not happen along the way: no field was trimmed into a fresh buffer, uppercased, or copied in order to be compared. matches! compares the bytes where they already are.
Common Mistakes
- Treating an out-of-range slice as a compile error.
&v[1..5]on a three-elementvbuilds fine and panics when it runs. If the endpoints came from anywhere other than a literal you wrote yourself, reach forv.get(1..5)and handle theNone.
- Reading
s.len()as a character count. On a&strit is a byte count. For ASCII the two agree, which is exactly why the bug survives testing and appears the first time a user types an accented name.
- Writing
s[0]on a string. It does not compile --strhas noIndex<usize>implementation. Say what you mean:s.as_bytes()[0]for a byte,s.chars().next()for a character.
- Slicing a string at an offset you did not check.
&s[..n]wherensplits a multi-byte character panics.s.get(..n)givesNoneinstead, ands.is_char_boundary(n)lets you ask first.
- Holding a slice into a
Vecacross apush. The push may reallocate and move every element, so the slice would point at freed memory.let first = &v[0]; v.push(4); println!("{first}");is rejected witherror[E0502]. Copy the value out, or finish with the slice before growing the vector.
- Taking
&Vec<T>or&Stringas a parameter. It works, but it needlessly refuses arrays, other slices and string literals. Take&[T]and&str; deref coercion means every existing caller keeps working unchanged. Clippy'sptr_arglint flags this.
- Confusing
[T; N]with&[T]. Passing an array by value copies every element; passing a slice copies two words. A function taking[u8; 1024]by value moves a kilobyte on every call, and the signature looks almost identical to the one that does not.
- Reaching for
windowswhen you wantedchunks.windows(2)over four elements yields three overlapping pairs;chunks(2)yields two disjoint pairs. Summing a batch withwindowsdouble-counts almost everything. Both panic on a size of zero.
- Calling
.sort()on a slice of floats. It does not compile, becausef64isPartialOrdbut notOrd--NaNhas no place in a total order. Usev.sort_by(|a, b| a.total_cmp(b)), which defines one.
Best Practices
- Accept
&[T]and&strin function signatures and return owned types only when the caller genuinely needs to keep the data. This one habit removes most unnecessary allocation from parsing and formatting code.
- Use indexing when an out-of-range value means your own code has a bug, and
getwhen the index arrived from outside the program. The choice documents which one you believe it is.
- Reach for
split_at_mut,chunks_mutoriter_mutwhen you need to mutate parts of a collection at once, rather than fighting the borrow checker with indices andclone.
- Prefer
first(),last()andsplit_first()overv[0]andv[v.len() - 1]. They returnOption, andv[v.len() - 1]additionally underflows on an empty vector before it even indexes.
- Keep byte offsets and character positions in separate variables with names that say which they are, and get offsets from
char_indices,findorsplitrather than arithmetic.
- Let slices carry their own length. A signature like
fn sum(xs: &[i32], n: usize)invites the two arguments to disagree;fn sum(xs: &[i32])cannot.
- Use
Box<[T]>instead ofVec<T>for a collection that is finished growing. It drops the capacity word and makes "this will not change size" part of the type.
- Do the whole job with the slice before you touch the owner. Non-lexical lifetimes end the borrow at its last use, so simply moving the mutation after the final read resolves most
E0502errors without restructuring anything.
Practice Exercises
- Safe window. Write
fn window(v: &[i32], start: usize, len: usize) -> &[i32]that returns the requested run of elements, clamped to what actually exists, and returns an empty slice whenstartis past the end. Do it without any panicking index. Verify it against(0, 3),(3, 99)and(99, 1)on a five-element slice.
- Longest word. Write
fn longest(text: &str) -> &strthat returns the longest whitespace-separated word, or an empty string for input with no words. Return a slice of the input rather than aString, and confirm that ties go to the first of the tied words.
- In-place normalisation. Write
fn clamp_all(scores: &mut [i32], lo: i32, hi: i32) -> usizethat clamps every element into the range and returns how many it changed. Then usesplit_at_mutto clamp the first half to0..=50and the second half to0..=100in a single pass, and print the array before and after.
- Zero-copy CSV field. Write
fn field(line: &str, n: usize) -> Option<&str>that returns thenth comma-separated field of a line, trimmed, without allocating. Handle a missing field, an empty field between two commas, and a trailing comma. Then explain in one sentence why the returned&strcannot outliveline.