You can easily do this with the TryInto trait (which was stabilized in Rust 1.34):

// Before Rust 2021, you need to import the trait:
// use std::convert::TryInto;

fn pop(barry: &[u8]) -> [u8; 3] {
    barry.try_into().expect("slice should have length 3")
}

But even better: there is no need to clone/copy your elements! It is actually possible to get a &[u8; 3] from a &[u8]:

fn pop(barry: &[u8]) -> &[u8; 3] {
    barry.try_into().expect("slice should have length 3")
}

As mentioned in the other answers, you probably don't want to panic if the length of barry is not 3, but instead handle this error gracefully.

This works thanks to these impls of the related trait TryFrom (before Rust 1.47, these only existed for arrays up to length 32):

impl<'_, T, const N: usize> TryFrom<&'_ [T]> for [T; N]
where
    T: Copy, 

impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]

impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
Answer from Lukas Kalbertodt on Stack Overflow
๐ŸŒ
Rust
doc.rust-lang.org โ€บ std โ€บ primitive.slice.html
slice - Rust
Gets a mutable (unique) reference to the contained value. Calling this when the content is not yet fully initialized causes undefined behavior: it is up to the caller to guarantee that every MaybeUninit<T> in the slice really is in an initialized state.
๐ŸŒ
The Rust Programming Language
doc.rust-lang.org โ€บ book โ€บ ch04-03-slices.html
The Slice Type - The Rust Programming Language
When we find a space, we return a string slice using the start of the string and the index of the space as the starting and ending indices. Now when we call first_word, we get back a single value that is tied to the underlying data.
Discussions

How to get a slice as an array in Rust? - Stack Overflow
I'm new to Rust. What was not clear with the other answers is if we could vary the length of the fixed array being returned. I couldn't figure out how to do this with a function so resorted to a macro. You're right the return is a habit ๐Ÿ˜‰ 2019-06-01T13:20:35.627Z+00:00 ... Save this answer. ... Show activity on this post. The nice common thing between Vec, 'Slice... More on stackoverflow.com
๐ŸŒ stackoverflow.com
vector - How do I get a slice of a Vec<T> in Rust? - Stack Overflow
I can not find within the documentation of Vec how to retrieve a slice from a specified range. Is there something like this in the standard library: let a = vec![1, 2, 3, 4]; let suba = a. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Cleanest way to get the index of an element in a slice by pointer/reference?
let slice = &[1, 2, 3, 4]; let elem = &slice[2]; let slice_ptr = slice.as_ptr() as usize; let elem_ptr = elem as *const i32 as usize; let index = elem_ptr - slice_ptr; Results are unpredictable if elem is not a reference to an element in slice. More on reddit.com
๐ŸŒ r/rust
15
12
December 24, 2021
rust - How to get address of a slice? - Stack Overflow
How to convert slice to either *const () or usize? &[ T ] -> *const () Of course, I understand it will downgrade fat pointer to slim one dropping length. My use case is comparing addresses ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Programiz
programiz.com โ€บ rust โ€บ slice
Rust Slice (With Examples)
A Rust slice is a data type used to access portions of data stored in collections like arrays, vectors and strings.
Top answer
1 of 9
206

You can easily do this with the TryInto trait (which was stabilized in Rust 1.34):

// Before Rust 2021, you need to import the trait:
// use std::convert::TryInto;

fn pop(barry: &[u8]) -> [u8; 3] {
    barry.try_into().expect("slice should have length 3")
}

But even better: there is no need to clone/copy your elements! It is actually possible to get a &[u8; 3] from a &[u8]:

fn pop(barry: &[u8]) -> &[u8; 3] {
    barry.try_into().expect("slice should have length 3")
}

As mentioned in the other answers, you probably don't want to panic if the length of barry is not 3, but instead handle this error gracefully.

This works thanks to these impls of the related trait TryFrom (before Rust 1.47, these only existed for arrays up to length 32):

impl<'_, T, const N: usize> TryFrom<&'_ [T]> for [T; N]
where
    T: Copy, 

impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]

impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
2 of 9
24

Thanks to @malbarbo we can use this helper function:

use std::convert::AsMut;

fn clone_into_array<A, T>(slice: &[T]) -> A
where
    A: Default + AsMut<[T]>,
    T: Clone,
{
    let mut a = A::default();
    <A as AsMut<[T]>>::as_mut(&mut a).clone_from_slice(slice);
    a
}

to get a much neater syntax:

fn main() {
    let original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    let e = Example {
        a: clone_into_array(&original[0..4]),
        b: clone_into_array(&original[4..10]),
    };

    println!("{:?}", e);
}

as long as T: Default + Clone.

If you know your type implements Copy, you can use this form:

use std::convert::AsMut;

fn copy_into_array<A, T>(slice: &[T]) -> A
where
    A: Default + AsMut<[T]>,
    T: Copy,
{
    let mut a = A::default();
    <A as AsMut<[T]>>::as_mut(&mut a).copy_from_slice(slice);
    a
}

Both variants will panic! if the target array and the passed-in slice do not have the same length.

๐ŸŒ
Rust
doc.rust-lang.org โ€บ std โ€บ slice โ€บ index.html
std::slice - Rust
A few functions are provided to create a slice from a value reference or from a raw pointer.
๐ŸŒ
KoderHQ
koderhq.com โ€บ tutorial โ€บ rust โ€บ slice
Rust Slices Tutorial | KoderHQ
In this Rust tutorial we learn how to create subsets of elements of arrays, vectors and strings by slicing them, allowing us to access data in contiguous memory blocks safely and efficiently. ... A slice in Rust is a data type that doesnโ€™t have an owner, itโ€™s just a pointer to a block of memory.
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ @trivajay259 โ€บ how-to-get-a-slice-as-an-array-in-rust-without-losing-your-mind-76133938609a
How to Get a Slice as an Array in Rust (Without Losing Your Mind) | by Ajay Kumar | Medium
March 10, 2026 - How to Get a Slice as an Array in Rust (Without Losing Your Mind) You have an array or slice in Rust. You know it definitely has (at least) three elements. You want a nice, clean [u8; 3] out of โ€ฆ
๐ŸŒ
DEV Community
dev.to โ€บ francescoxx โ€บ slices-in-rust-g6
Slices in Rust - DEV Community
March 5, 2024 - The Slice type in Rust Rust has a built-in type called Slice that is used to reference a...
๐ŸŒ
MIT
web.mit.edu โ€บ rust-lang_v1.25 โ€บ arch โ€บ amd64_ubuntu1404 โ€บ share โ€บ doc โ€บ rust โ€บ html โ€บ book โ€บ second-edition โ€บ ch04-03-slices.html
Slices - The Rust Programming Language
The concepts of ownership, borrowing, and slices are what ensure memory safety in Rust programs at compile time. The Rust language gives you control over your memory usage like other systems programming languages, but having the owner of data automatically clean up that data when the owner goes out of scope means you donโ€™t have to write and debug extra code to get this control.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ rust โ€บ rust_slices.htm
Rust - Slices
A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data.
๐ŸŒ
Rust By Example
doc.rust-lang.org โ€บ rust-by-example โ€บ primitives โ€บ array.html
Arrays and Slices - Rust By Example
// `ending_index` is one more than the last position in the slice. println!("Borrow a section of the array as a slice."); analyze_slice(&ys[1 .. 4]); // Example of empty slice `&[]`: let empty_array: [u32; 0] = []; assert_eq!(&empty_array, &[]); assert_eq!(&empty_array, &[][..]); // Same but more verbose // Arrays can be safely accessed using `.get`, which returns an // `Option`. This can be matched as shown below, or used with // `.expect()` if you would like the program to exit with a nice // message instead of happily continue.
๐ŸŒ
Reddit
reddit.com โ€บ r/rust โ€บ is there a way to get the range of a slice?
r/rust on Reddit: Is there a way to get the Range of a slice?
July 26, 2023 -

I canโ€™t seem to find any such function in the docs. Is there a way to get the range from a slice? eg. s[1..3] creates a slice of s from the range [1..3]. I want an inverse function to get the range [1..3] from the slice of s. The function would have to be the range with respect to the owning structure of course, otherwise the function wouldn't be well defined as you can take a slice of a slice. eg. s[2..9][1..3] (The "inverse" of which should be [3..5]).

๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ rust โ€บ slices
Rust | Slices | Codecademy
May 15, 2024 - A quick primer on the fundamentals of the Rust programming language for experienced programmers. ... The syntax for a slice in Rust is represented as &[T], where T is the element type.
๐ŸŒ
NAPALM
saidvandeklundert.net โ€บ 2021-08-14-rust-slice
Rust slice
August 14, 2021 - The string slice is a &str, so we would not be able to pass it into the return_second function. In fact, the string slice is a bit โ€˜specialโ€™. All strings in Rust are UTF-8 and therefore, characters can differ in size. The iter() does not work on string slices, instead, we need to turn to chars().
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ rust โ€บ rust-slices
Rust - Slices - GeeksforGeeks
March 15, 2021 - // Rust program for slicing Array fn main() { let gfg = [10, 22, 31, 43, 57]; let length_of_array=gfg.len(); let x=2; // for first value println!("for first= {:?}",&gfg[0..1]); // for first three value println!("for first three= {:?}",&gfg[0..3]); // for first to last(or length) println!("for 0 to length of the array= {:?}",&gfg[0..length_of_array] ); println!("{:?}",&gfg[x..length_of_array]); }
๐ŸŒ
DEV Community
dev.to โ€บ itachiuchiha โ€บ a-slice-of-rust-working-with-the-slice-type-4p8i
A Slice of Rust: Working with the Slice Type - DEV Community
August 3, 2020 - Hello world. We also have slices by this example. These are; When you want to get a part of a string, you should use a range within brackets by specifying.
๐ŸŒ
The Rust Programming Language
doc.rust-lang.org โ€บ nightly โ€บ core โ€บ slice โ€บ index.html
core::slice - Rust
A helper trait for <[T]>::get_disjoint_mut(). ... Patterns in slices - currently, only used by strip_prefix and strip_suffix.