Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a slice into an array reference?

Tags:

arrays

slice

rust

I have an &[u8] and would like to turn it into an &[u8; 3] without copying. It should reference the original array. How can I do this?

like image 295
SoniEx2 Avatar asked Jan 06 '18 16:01

SoniEx2


People also ask

Is a slice an array?

The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.

How do you convert a slice to a vector in Rust?

To create a new vector from a slice: slice. to_vec();

How do I slice an array in Golang?

creating a slice using make func make([]T, len, cap) []T can be used to create a slice by passing the type, length and capacity. The capacity parameter is optional and defaults to the length. The make function creates an array and returns a slice reference to it.

What is array slice explain with example?

Common examples of array slicing are extracting a substring from a string of characters, the "ell" in "hello", extracting a row or column from a two-dimensional array, or extracting a vector from a matrix. Depending on the programming language, an array slice can be made out of non-consecutive elements.


1 Answers

As of Rust 1.34, you can use TryFrom / TryInto:

use std::convert::TryFrom;

fn example(slice: &[u8]) {
    let array = <&[u8; 3]>::try_from(slice);
    println!("{:?}", array);
}

fn example_mut(slice: &mut [u8]) {
    let array = <&mut [u8; 3]>::try_from(slice);
    println!("{:?}", array);
}
like image 91
Shepmaster Avatar answered Nov 03 '22 17:11

Shepmaster