Slices as borrowed views
Quick answer
A slice is a view into a contiguous sequence of elements. A borrowed slice such as &[i32] carries access to the sequence and its length without owning the elements.
Half-open ranges
Use &array[start..end] to borrow elements from start up to, but not including, end. An omitted start means zero and an omitted end means the length. Invalid ranges panic. A function accepting &[i32] can operate on arrays and other contiguous integer sequences via borrowing. A mutable slice &mut [i32] provides exclusive access to its elements.
fn main() { let data = [10, 20, 30, 40]; let middle = &data[1..3]; println!("{} {}", middle[0], middle.len());}Expected stdout (not executed):
20 2Indices within middle start again at zero.
fn zero_first(values: &mut [i32]) { if !values.is_empty() { values[0] = 0; }}fn main() { let mut data = [10, 20, 30]; zero_first(&mut data[1..]); println!("{data:?}");}Expected stdout (not executed):
[10, 0, 30]The first element of the borrowed suffix corresponds to index one of data.
Common mistake
Do not treat the end index as inclusive; 1..3 covers two elements.
Try it yourself
Borrow the last two elements of an array of five integers and write a function to sum them.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slices as borrowed views — practice quiz
Choose one answer per question, then review the explanation.
What does `&[1,2,3,4][..2]` view?
Does creating an ordinary borrowed array slice allocate a separate copy of the elements?
Which slice type allows changing elements through the slice?