Skip to content

Commit d02a209

Browse files
committed
Auto merge of #75028 - MrModder:master, r=steveklabnik
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
2 parents 9d606d9 + cf76256 commit d02a209

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

library/std/src/primitive_docs.rs

+14
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,20 @@ mod prim_array {}
587587
/// x[1] = 7;
588588
/// assert_eq!(x, &[1, 7, 3]);
589589
/// ```
590+
///
591+
/// As slices store the length of the sequence they refer to, they have twice
592+
/// the size of pointers to [`Sized`](marker/trait.Sized.html) types.
593+
/// Also see the reference on
594+
/// [dynamically sized types](../reference/dynamically-sized-types.html).
595+
///
596+
/// ```
597+
/// # use std::rc::Rc;
598+
/// let pointer_size = std::mem::size_of::<&u8>();
599+
/// assert_eq!(2 * pointer_size, std::mem::size_of::<&[u8]>());
600+
/// assert_eq!(2 * pointer_size, std::mem::size_of::<*const [u8]>());
601+
/// assert_eq!(2 * pointer_size, std::mem::size_of::<Box<[u8]>>());
602+
/// assert_eq!(2 * pointer_size, std::mem::size_of::<Rc<[u8]>>());
603+
/// ```
590604
#[stable(feature = "rust1", since = "1.0.0")]
591605
mod prim_slice {}
592606

0 commit comments

Comments
 (0)