Rust

Slice (Rust)

A slice is a reference to a contiguous subrange of a collection, like a substring of a String or a window into a Vec.

Why slices?

You often want part of a collection without copying it. A slice is a lightweight borrow (pointer plus length) that avoids allocation while still being bounds-checked.

String slices

let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];

Slices also work on vectors and other collections. Because a slice is a reference, it follows the borrow rules: while a slice exists, the underlying collection can’t be mutated.