# Creating slices

**URL:** <https://users.rust-lang.org/t/creating-slices/54273>\
**Category:** help\
**Created:** [January 17, 2021, 11:52am UTC](https://users.rust-lang.org/t/creating-slices/54273 "2021-01-17T11:52:06Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![mvolkmann](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/mvolkmann/32/18387_2.png) [@mvolkmann](https://users.rust-lang.org/u/mvolkmann)\
**Post date:** [January 17, 2021, 11:52am UTC](https://users.rust-lang.org/t/creating-slices/54273/1 "2021-01-17T11:52:07Z")

</div>

All the examples I see of creating slices use range syntax. Is it true that that is the only way to create a slice? I don't think I have seen any methods on built-in types that return a slice, but maybe I just overlooked them.

---

<div class="post-metadata">

**Author:** ![Cerber-Ursi](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cerber-ursi/32/8315_2.png) [@Cerber-Ursi](https://users.rust-lang.org/u/Cerber-Ursi)\
**Post date:** [January 17, 2021, 11:54am UTC](https://users.rust-lang.org/t/creating-slices/54273/2 "2021-01-17T11:54:33Z")

</div>

Do [`Vec::as_slice`](https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.as_slice) and similar ones count?

---

<div class="post-metadata">

**Author:** ![mvolkmann](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/mvolkmann/32/18387_2.png) [@mvolkmann](https://users.rust-lang.org/u/mvolkmann)\
**Post date:** [January 17, 2021, 12:05pm UTC](https://users.rust-lang.org/t/creating-slices/54273/3 "2021-01-17T12:05:11Z")

</div>

While technically that creates a slice, I'm looking for ways to create slices that represent a subset of a collection rather than all of it.

---

<div class="post-metadata">

**Author:** ![Cerber-Ursi](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cerber-ursi/32/8315_2.png) [@Cerber-Ursi](https://users.rust-lang.org/u/Cerber-Ursi)\
**Post date:** [January 17, 2021, 12:06pm UTC](https://users.rust-lang.org/t/creating-slices/54273/4 "2021-01-17T12:06:27Z")

</div>

Slice is, by definition, a contiguous chunk of memory. So any way to create a subslice of collection will be semantically equivalent to indexing with range.

---

<div class="post-metadata">

**Author:** ![mvolkmann](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/mvolkmann/32/18387_2.png) [@mvolkmann](https://users.rust-lang.org/u/mvolkmann)\
**Post date:** [January 17, 2021, 12:08pm UTC](https://users.rust-lang.org/t/creating-slices/54273/5 "2021-01-17T12:08:18Z")

</div>

This is exactly what I'm looking for ... other ways to do this besides using a range. What other ways exist?

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [January 17, 2021, 1:02pm UTC](https://users.rust-lang.org/t/creating-slices/54273/6 "2021-01-17T13:02:52Z")

</div>

With unsafe you can create a slice through `std::slice::from_raw_parts` by providing a pointer and length.

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [January 17, 2021, 1:04pm UTC](https://users.rust-lang.org/t/creating-slices/54273/7 "2021-01-17T13:04:30Z")

</div>

You can also use [`from_ref`](https://doc.rust-lang.org/stable/std/slice/fn.from_ref.html) to turn an `&T` into a slice `&[T]` of length one.

---

<div class="post-metadata">

**Author:** ![Michael-F-Bryan](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/michael-f-bryan/32/28749_2.png) [@Michael-F-Bryan](https://users.rust-lang.org/u/Michael-F-Bryan)\
**Post date:** [January 17, 2021, 2:06pm UTC](https://users.rust-lang.org/t/creating-slices/54273/8 "2021-01-17T14:06:35Z")

</div>

At the end of the day, a slice is just a pointer to the first element and a length, so all methods of creating one will reduce to some pointer arithmetic (to calculate where the first element is) and bounds check (to make sure the slice doesn't include invalid memory) in some form or another.

Everything else is just smoke and mirrors and layers of abstraction to help maintain memory safety, correctness, and ergonomics.

In the case of `&some_slice[start..end]`, this expression boils down to [this piece of code](https://github.com/rust-lang/rust/blob/d51cf9601c714a8383aecade7c98559dd4831625/library/core/src/slice/index.rs#L222):

```rust
unsafe impl<T> SliceIndex<[T]> for ops::Range<usize> {
    type Output = [T];

    #[inline]
    fn get(self, slice: &[T]) -> Option<&[T]> {
        if self.start > self.end || self.end > slice.len() {
            None
        } else {
            // SAFETY: `self` is checked to be valid and in bounds above.
            unsafe { Some(&*self.get_unchecked(slice)) }
        }
    }

    #[inline]
    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
        // SAFETY: the caller guarantees that `slice` is not dangling, so it
        // cannot be longer than `isize::MAX`. They also guarantee that
        // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
        // so the call to `add` is safe.
        unsafe { ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start) }
    }
}

```

Where [`ptr::slice_from_raw_parts()`](https://github.com/rust-lang/rust/blob/d51cf9601c714a8383aecade7c98559dd4831625/library/core/src/ptr/mod.rs#L269-L273) (who's stable form callable via `std::slice::from_raw_parts()`) is defined by `unsafe`-ly reinterpreting the pointer and length as a raw slice.

```rust
#[repr(C)]
union Repr<T> {
    rust: *const [T],
    rust_mut: *mut [T],
    raw: FatPtr<T>,
}

#[repr(C)]
struct FatPtr<T> {
    data: *const T,
    len: usize,
}

pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
    // SAFETY: Accessing the value from the `Repr` union is safe since *const [T]
    // and FatPtr have the same memory layouts. Only std can make this
    // guarantee.
    unsafe { Repr { raw: FatPtr { data, len } }.rust }
}

```

---

<div class="post-metadata">

**Author:** ![cole-miller](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cole-miller/32/16722_2.png) [@cole-miller](https://users.rust-lang.org/u/cole-miller)\
**Post date:** [January 17, 2021, 2:07pm UTC](https://users.rust-lang.org/t/creating-slices/54273/9 "2021-01-17T14:07:56Z")

</div>

Many [slice methods](https://doc.rust-lang.org/std/primitive.slice.html) return further slices or iterators over the same (e.g. `chunks`).

---

<div class="post-metadata">

**Author:** ![kornel](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/kornel/32/4823_2.png) [@kornel](https://users.rust-lang.org/u/kornel)\
**Post date:** [January 18, 2021, 9:02pm UTC](https://users.rust-lang.org/t/creating-slices/54273/10 "2021-01-18T21:02:45Z")

</div>

> I'm looking for ways to create slices that represent a subset of a collection rather than all of it.

A long slice can be shortened, so std types don't bother having methods for subsets. You can get a full-sized slice and then use the range syntax to shorten it. Since it's a cheap operation and a built-in syntax, there's no need for types to provide custom methods for it.

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/skifire13/32/17959_2.png) [@SkiFire13](https://users.rust-lang.org/u/SkiFire13)\
**Post date:** [January 18, 2021, 9:54pm UTC](https://users.rust-lang.org/t/creating-slices/54273/11 "2021-01-18T21:54:00Z")

</div>

Also technically you could call [iter](https://doc.rust-lang.org/std/primitive.slice.html#method.iter) on a slice, consume part of the iterator, and then call [`as_slice`](https://doc.rust-lang.org/std/slice/struct.Iter.html#method.as_slice) on it to get the remaining slice (i.e. without the yielded items). However, please don't do this.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [April 18, 2021, 9:54pm UTC](https://users.rust-lang.org/t/creating-slices/54273/12 "2021-04-18T21:54:00Z")

</div>

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
