diff options
| author | bors <bors@rust-lang.org> | 2020-08-23 16:59:10 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2020-08-23 16:59:10 +0000 |
| commit | d02a209eb946929801882d884b459f438d9650d2 (patch) | |
| tree | 5709406a25ae340a0037faa7ff2c69079a9551fe | |
| parent | 9d606d939a61c2f4c7bb4d89d959b60a53f50241 (diff) | |
| parent | cf76256b83d7ccbf1d673c4bcb3ad0d1bd904315 (diff) | |
| download | rust-d02a209eb946929801882d884b459f438d9650d2.tar.gz rust-d02a209eb946929801882d884b459f438d9650d2.zip | |
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
| -rw-r--r-- | library/std/src/primitive_docs.rs | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/library/std/src/primitive_docs.rs b/library/std/src/primitive_docs.rs index bca1732b84d..be7fd0dd6c4 100644 --- a/library/std/src/primitive_docs.rs +++ b/library/std/src/primitive_docs.rs @@ -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 {} |
