Skip to content

Commit

Permalink
Auto merge of #75028 - MrModder:master, r=steveklabnik
Browse files Browse the repository at this point in the history
Document that slice refers to any pointer type to a sequence

I was recently confused about the way slices are represented in memory. The necessary information was not available in the std-docs directly, but was a mix of different material from the reference and book.

This PR should clear up the definition of slices a bit more in the documentation. Especially the fact that the term slice refers to the pointer/reference type, e.g. `&[T]`, and not `[T]`.
It also documents that slice pointers are twice the size of pointers to `Sized` types, as this concept may be unfamiliar to users coming from other languages that do not have the concept of "fat pointers" (especially C/C++).

I've documented why this was important to me and my findings in [this blog post](https://codecrash.me/understanding-rust-slices).

r? @lcnr
  • Loading branch information
bors committed Aug 23, 2020
2 parents 9d606d9 + cf76256 commit d02a209
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions library/std/src/primitive_docs.rs
Expand Up @@ -587,6 +587,20 @@ mod prim_array {}
/// x[1] = 7;
/// assert_eq!(x, &[1, 7, 3]);
/// ```
///
/// As slices store the length of the sequence they refer to, they have twice
/// the size of pointers to [`Sized`](marker/trait.Sized.html) types.
/// Also see the reference on
/// [dynamically sized types](../reference/dynamically-sized-types.html).
///
/// ```
/// # use std::rc::Rc;
/// let pointer_size = std::mem::size_of::<&u8>();
/// assert_eq!(2 * pointer_size, std::mem::size_of::<&[u8]>());
/// assert_eq!(2 * pointer_size, std::mem::size_of::<*const [u8]>());
/// assert_eq!(2 * pointer_size, std::mem::size_of::<Box<[u8]>>());
/// assert_eq!(2 * pointer_size, std::mem::size_of::<Rc<[u8]>>());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
mod prim_slice {}

Expand Down

0 comments on commit d02a209

Please sign in to comment.