liveBook · Manning

Slicing

As explained in Idiomatic Rust

A slice is a dynamically sized view of a contiguous sequence without owning the underlying storage.

A slice is a borrowed view of a contiguous sequence, not an owner of its storage. Use &[T] when a function needs to read a sequence without requiring a particular collection type. section 6.4

Slices are useful at API boundaries:

  • Accept &[T] instead of &Vec<T> to allow inputs such as vectors and arrays. section 6.4
  • Return a slice from an accessor when callers need to read contiguous data without receiving the collection itself. section 4.4
  • Use &str to pass string data by reference. section 4.2.2
fn do_something_with_slice<T>(v: &[T]) {
    // ...
}

Compare the Vec-specific input with the slice-based signature for a more flexible function interface. section 6.4

How Idiomatic Rust covers it

How deep it goes
Compares Vec- and slice-based input signatures and demonstrates a slice-returning accessor, staying at the interface level.
Examples
Demonstrates a pizza-toppings accessor, flexible collection inputs, and string reversal using &str.
What you can do after
Apply slices by accepting &[T] instead of &Vec<T> in library function interfaces.
How it connects
Connects slices with Vec, arrays, iterators, and borrowed references.

Also explained in

Compare how 16 books explain slicing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.