liveBook · Manning

Slicing

As explained in Refactoring to Rust

A slice is a non-owning view of a contiguous region of elements represented by a pointer and a length.

A slice is a borrowed view of a contiguous region of elements. It holds a pointer to the first element and a length; it does not own or copy the underlying data. A string slice, `&str`, is a read-only view of string data. Several `&str` values can point to different parts of the same `String`. section 4.4.2 section 4.7

Figure 4.8 Taking multiple slices of the same string
figure

The figure shows multiple string slices pointing into one `String`, rather than each holding a separate copy. section 4.4.2

That distinction matters when choosing between borrowing and ownership. Getting an `&str` from a `String` is cheap: the view needs only the buffer’s starting pointer and length. Calling `.to_string()` on an `&str` instead creates an owned `String`, allocating a buffer and copying the data. Substring operations on `&str` need not reallocate memory. section 2.4.1 section 3.3

Borrowing an NGINX request body

A function returning `Result<&'a str, &'static str>` from a `&'a ngx_http_request_t` ties the returned string slice to the request’s lifetime. The slice views memory owned by the request; it cannot remain valid after that request is deallocated. section 4.4.2

To form a view of request memory reached through C pointers:

  • Check that the request-body buffer pointers are initialized before following them. section 4.4.2
  • Determine the region’s length from its start and end pointers using `.offset_from`. section 4.4.2 section 4.7
  • Use `std::slice::from_raw_parts` to construct a slice from a pointer and length. Because raw-pointer operations can require `unsafe`, the developer must uphold the memory-safety rules the compiler cannot check. section 4.7 section 3.3

How Refactoring to Rust covers it

How deep it goes
Defines pointer-and-length views, explains their lifetimes, and shows the raw-pointer operations used to construct a request-body view.
Examples
Illustrates multiple `&str` views into one `String` and a string slice borrowed from NGINX request buffers.
What it assumes
Builds from arrays, vectors, and `String` versus `&str` before introducing raw-pointer FFI.
What you can do after
Apply it via Rust `&str` and `std::slice::from_raw_parts` to view existing data while respecting its lifetime.
How it connects
Connects slices to `String`, `&str`, lifetimes, raw pointers, and C FFI.

Also explained in

Compare how 16 books explain slicing →

Related concepts

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