array - Rust (original) (raw)

Primitive Type array

1.0.0

Expand description

A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N.

There are two syntactic forms for creating an array:

Note that [expr; 0] is allowed, and produces an empty array. This will still evaluate expr, however, and immediately drop the resulting value, so be mindful of side effects.

Arrays of any size implement the following traits if the element type allows it:

Arrays of sizes from 0 to 32 (inclusive) implement the Default trait if the element type allows it. As a stopgap, trait implementations are statically generated up to size 32.

Arrays of sizes from 1 to 12 (inclusive) implement From, where Tupleis a homogeneous tuple of appropriate length.

Arrays coerce to slices ([T]), so a slice method may be called on an array. Indeed, this provides most of the API for working with arrays.

Slices have a dynamic size and do not coerce to arrays. Instead, useslice.try_into().unwrap() or <ArrayType>::try_from(slice).unwrap().

Array’s try_from(slice) implementations (and the corresponding slice.try_into()array implementations) succeed if the input slice length is the same as the result array length. They optimize especially well when the optimizer can easily determine the slice length, e.g. <[u8; 4]>::try_from(&slice[4..8]).unwrap(). Array implementsTryFrom returning:

You can move elements out of an array with a slice pattern. If you want one element, see mem::replace.

§Examples

let mut array: [i32; 3] = [0; 3];

array[1] = 1;
array[2] = 2;

assert_eq!([1, 2], &array[1..]);

// This loop prints: 0 1 2
for x in array {
    print!("{x} ");
}

You can also iterate over reference to the array’s elements:

let array: [i32; 3] = [0; 3];

for x in &array { }

You can use <ArrayType>::try_from(slice) or slice.try_into() to get an array from a slice:

let bytes: [u8; 3] = [1, 0, 2];
assert_eq!(1, u16::from_le_bytes(<[u8; 2]>::try_from(&bytes[0..2]).unwrap()));
assert_eq!(512, u16::from_le_bytes(bytes[1..3].try_into().unwrap()));

You can use a slice pattern to move elements out of an array:

fn move_away(_: String) { /* Do interesting things. */ }

let [john, roa] = ["John".to_string(), "Roa".to_string()];
move_away(john);
move_away(roa);

Arrays can be created from homogeneous tuples of appropriate length:

let tuple: (u32, u32, u32) = (1, 2, 3);
let array: [u32; 3] = tuple.into();

§Editions

Prior to Rust 1.53, arrays did not implement IntoIterator by value, so the method callarray.into_iter() auto-referenced into a slice iterator. Right now, the old behavior is preserved in the 2015 and 2018 editions of Rust for compatibility, ignoringIntoIterator by value. In the future, the behavior on the 2015 and 2018 edition might be made consistent to the behavior of later editions.

// Rust 2015 and 2018:

let array: [i32; 3] = [0; 3];

// This creates a slice iterator, producing references to each value.
for item in array.into_iter().enumerate() {
    let (i, x): (usize, &i32) = item;
    println!("array[{i}] = {x}");
}

// The `array_into_iter` lint suggests this change for future compatibility:
for item in array.iter().enumerate() {
    let (i, x): (usize, &i32) = item;
    println!("array[{i}] = {x}");
}

// You can explicitly iterate an array by value using `IntoIterator::into_iter`
for item in IntoIterator::into_iter(array).enumerate() {
    let (i, x): (usize, i32) = item;
    println!("array[{i}] = {x}");
}

Starting in the 2021 edition, array.into_iter() uses IntoIterator normally to iterate by value, and iter() should be used to iterate by reference like previous editions.

// Rust 2021:

let array: [i32; 3] = [0; 3];

// This iterates by reference:
for item in array.iter().enumerate() {
    let (i, x): (usize, &i32) = item;
    println!("array[{i}] = {x}");
}

// This iterates by value:
for item in array.into_iter().enumerate() {
    let (i, x): (usize, i32) = item;
    println!("array[{i}] = {x}");
}

Future language versions might start treating the array.into_iter()syntax on editions 2015 and 2018 the same as on edition 2021. So code using those older editions should still be written with this change in mind, to prevent breakage in the future. The safest way to accomplish this is to avoid the into_iter syntax on those editions. If an edition update is not viable/desired, there are multiple alternatives:

// Rust 2015 and 2018:

let array: [i32; 3] = [0; 3];

// This iterates by reference:
for item in array.iter() {
    let x: &i32 = item;
    println!("{x}");
}

// This iterates by value:
for item in IntoIterator::into_iter(array) {
    let x: i32 = item;
    println!("{x}");
}

// This iterates by value:
for item in array {
    let x: i32 = item;
    println!("{x}");
}

// IntoIter can also start a chain.
// This iterates by value:
for item in IntoIterator::into_iter(array).enumerate() {
    let (i, x): (usize, i32) = item;
    println!("array[{i}] = {x}");
}

Source§

Source

🔬This is a nightly-only experimental API. (maybe_uninit_uninit_array_transpose #96097)

Transposes a [MaybeUninit<T>; N] into a MaybeUninit<[T; N]>.

§Examples
#![feature(maybe_uninit_uninit_array_transpose)]

let data = [MaybeUninit::<u8>::uninit(); 1000];
let data: MaybeUninit<[u8; 1000]> = data.transpose();

Source§

Source

🔬This is a nightly-only experimental API. (ascii_char #110998)

Converts this array of bytes into an array of ASCII characters, or returns None if any of the characters is non-ASCII.

§Examples
#![feature(ascii_char)]

const HEX_DIGITS: [std::ascii::Char; 16] =
    *b"0123456789abcdef".as_ascii().unwrap();

assert_eq!(HEX_DIGITS[1].as_str(), "1");
assert_eq!(HEX_DIGITS[10].as_str(), "a");

Source

🔬This is a nightly-only experimental API. (ascii_char #110998)

Converts this array of bytes into an array of ASCII characters, without checking whether they’re valid.

§Safety

Every byte in the array must be in 0..=127, or else this is UB.

Source§

1.55.0 · Source

Returns an array of the same size as self, with function f applied to each element in order.

If you don’t necessarily need a new fixed-size array, consider usingIterator::map instead.

§Note on performance and stack usage

Unfortunately, usages of this method are currently not always optimized as well as they could be. This mainly concerns large arrays, as mapping over small arrays seem to be optimized just fine. Also note that in debug mode (i.e. without any optimizations), this method can use a lot of stack space (a few times the size of the array or more).

Therefore, in performance-critical code, try to avoid using this method on large arrays or check the emitted code. Also try to avoid chained maps (e.g. arr.map(...).map(...)).

In many cases, you can instead use Iterator::map by calling .iter()or .into_iter() on your array. [T; N]::map is only necessary if you really need a new array of the same size as the result. Rust’s lazy iterators tend to get optimized very well.

§Examples
let x = [1, 2, 3];
let y = x.map(|v| v + 1);
assert_eq!(y, [2, 3, 4]);

let x = [1, 2, 3];
let mut temp = 0;
let y = x.map(|v| { temp += 1; v * temp });
assert_eq!(y, [1, 4, 9]);

let x = ["Ferris", "Bueller's", "Day", "Off"];
let y = x.map(|v| v.len());
assert_eq!(y, [6, 9, 3, 3]);

Source

🔬This is a nightly-only experimental API. (array_try_map #79711)

A fallible function f applied to each element on array self in order to return an array the same size as self or the first error encountered.

The return type of this function depends on the return type of the closure. If you return Result<T, E> from the closure, you’ll get a Result<[T; N], E>. If you return Option<T> from the closure, you’ll get an Option<[T; N]>.

§Examples
#![feature(array_try_map)]

let a = ["1", "2", "3"];
let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
assert_eq!(b, [2, 3, 4]);

let a = ["1", "2a", "3"];
let b = a.try_map(|v| v.parse::<u32>());
assert!(b.is_err());

use std::num::NonZero;

let z = [1, 2, 0, 3, 4];
assert_eq!(z.try_map(NonZero::new), None);

let a = [1, 2, 3];
let b = a.try_map(NonZero::new);
let c = b.map(|x| x.map(NonZero::get));
assert_eq!(c, Some(a));

1.57.0 (const: 1.57.0) · Source

Returns a slice containing the entire array. Equivalent to &s[..].

1.57.0 (const: unstable) · Source

Returns a mutable slice containing the entire array. Equivalent to&mut s[..].

1.77.0 (const: unstable) · Source

Borrows each element and returns an array of references with the same size as self.

§Example
let floats = [3.1, 2.7, -1.0];
let float_refs: [&f64; 3] = floats.each_ref();
assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);

This method is particularly useful if combined with other methods, likemap. This way, you can avoid moving the original array if its elements are not Copy.

let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
let is_ascii = strings.each_ref().map(|s| s.is_ascii());
assert_eq!(is_ascii, [true, false, true]);

// We can still access the original array: it has not been moved.
assert_eq!(strings.len(), 3);

1.77.0 (const: unstable) · Source

Borrows each element mutably and returns an array of mutable references with the same size as self.

§Example

let mut floats = [3.1, 2.7, -1.0];
let float_refs: [&mut f64; 3] = floats.each_mut();
*float_refs[0] = 0.0;
assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
assert_eq!(floats, [0.0, 2.7, -1.0]);

Source

🔬This is a nightly-only experimental API. (split_array #90091)

Divides one array reference into two at an index.

The first will contain all indices from [0, M) (excluding the index M itself) and the second will contain all indices from [M, N) (excluding the index N itself).

§Panics

Panics if M > N.

§Examples
#![feature(split_array)]

let v = [1, 2, 3, 4, 5, 6];

{
   let (left, right) = v.split_array_ref::<0>();
   assert_eq!(left, &[]);
   assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
}

{
    let (left, right) = v.split_array_ref::<2>();
    assert_eq!(left, &[1, 2]);
    assert_eq!(right, &[3, 4, 5, 6]);
}

{
    let (left, right) = v.split_array_ref::<6>();
    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
    assert_eq!(right, &[]);
}

Source

🔬This is a nightly-only experimental API. (split_array #90091)

Divides one mutable array reference into two at an index.

The first will contain all indices from [0, M) (excluding the index M itself) and the second will contain all indices from [M, N) (excluding the index N itself).

§Panics

Panics if M > N.

§Examples
#![feature(split_array)]

let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.split_array_mut::<2>();
assert_eq!(left, &mut [1, 0][..]);
assert_eq!(right, &mut [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);

Source

🔬This is a nightly-only experimental API. (split_array #90091)

Divides one array reference into two at an index from the end.

The first will contain all indices from [0, N - M) (excluding the index N - M itself) and the second will contain all indices from [N - M, N) (excluding the index N itself).

§Panics

Panics if M > N.

§Examples
#![feature(split_array)]

let v = [1, 2, 3, 4, 5, 6];

{
   let (left, right) = v.rsplit_array_ref::<0>();
   assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
   assert_eq!(right, &[]);
}

{
    let (left, right) = v.rsplit_array_ref::<2>();
    assert_eq!(left, &[1, 2, 3, 4]);
    assert_eq!(right, &[5, 6]);
}

{
    let (left, right) = v.rsplit_array_ref::<6>();
    assert_eq!(left, &[]);
    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
}

Source

🔬This is a nightly-only experimental API. (split_array #90091)

Divides one mutable array reference into two at an index from the end.

The first will contain all indices from [0, N - M) (excluding the index N - M itself) and the second will contain all indices from [N - M, N) (excluding the index N itself).

§Panics

Panics if M > N.

§Examples
#![feature(split_array)]

let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.rsplit_array_mut::<4>();
assert_eq!(left, &mut [1, 0]);
assert_eq!(right, &mut [3, 0, 5, 6][..]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);

Source§

Source

🔬This is a nightly-only experimental API. (option_array_transpose #130828)

Transposes a [Option<T>; N] into a Option<[T; N]>.

§Examples
#![feature(option_array_transpose)]

let data = [Some(0); 1000];
let data: Option<[u8; 1000]> = data.transpose();
assert_eq!(data, Some([0; 1000]));

let data = [Some(0), None];
let data: Option<[u8; 2]> = data.transpose();
assert_eq!(data, None);

1.0.0 · Source§

Source§

Converts this type into a mutable reference of the (usually inferred) input type.

Source§

Source§

Converts this type into a mutable reference of the (usually inferred) input type.

1.0.0 · Source§

Source§

Converts this type into a shared reference of the (usually inferred) input type.

Source§

Source§

Converts this type into a shared reference of the (usually inferred) input type.

1.4.0 · Source§

1.4.0 · Source§

1.58.0 · Source§

1.0.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.4.0 · Source§

1.71.0 · Source§

This trait is implemented for tuples up to twelve items long.

Source§

Converts to this type from the input type.

Source§

Source§

Converts to this type from the input type.

Source§

Source§

Converts to this type from the input type.

1.17.0 · Source§

Source§

Creates an IpAddr::V6 from an eight element 16-bit array.

§Examples
use std:🥅:{IpAddr, Ipv6Addr};

let addr = IpAddr::from([
    0x20du16, 0x20cu16, 0x20bu16, 0x20au16,
    0x209u16, 0x208u16, 0x207u16, 0x206u16,
]);
assert_eq!(
    IpAddr::V6(Ipv6Addr::new(
        0x20d, 0x20c, 0x20b, 0x20a,
        0x209, 0x208, 0x207, 0x206,
    )),
    addr
);

1.16.0 · Source§

Source§

Creates an Ipv6Addr from an eight element 16-bit array.

§Examples
use std:🥅:Ipv6Addr;

let addr = Ipv6Addr::from([
    0x20du16, 0x20cu16, 0x20bu16, 0x20au16,
    0x209u16, 0x208u16, 0x207u16, 0x206u16,
]);
assert_eq!(
    Ipv6Addr::new(
        0x20d, 0x20c, 0x20b, 0x20a,
        0x209, 0x208, 0x207, 0x206,
    ),
    addr
);

1.17.0 · Source§

Source§

Creates an IpAddr::V6 from a sixteen element byte array.

§Examples
use std:🥅:{IpAddr, Ipv6Addr};

let addr = IpAddr::from([
    0x19u8, 0x18u8, 0x17u8, 0x16u8, 0x15u8, 0x14u8, 0x13u8, 0x12u8,
    0x11u8, 0x10u8, 0x0fu8, 0x0eu8, 0x0du8, 0x0cu8, 0x0bu8, 0x0au8,
]);
assert_eq!(
    IpAddr::V6(Ipv6Addr::new(
        0x1918, 0x1716, 0x1514, 0x1312,
        0x1110, 0x0f0e, 0x0d0c, 0x0b0a,
    )),
    addr
);

1.9.0 · Source§

Source§

Creates an Ipv6Addr from a sixteen element byte array.

§Examples
use std:🥅:Ipv6Addr;

let addr = Ipv6Addr::from([
    0x19u8, 0x18u8, 0x17u8, 0x16u8, 0x15u8, 0x14u8, 0x13u8, 0x12u8,
    0x11u8, 0x10u8, 0x0fu8, 0x0eu8, 0x0du8, 0x0cu8, 0x0bu8, 0x0au8,
]);
assert_eq!(
    Ipv6Addr::new(
        0x1918, 0x1716, 0x1514, 0x1312,
        0x1110, 0x0f0e, 0x0d0c, 0x0b0a,
    ),
    addr
);

1.17.0 · Source§

Source§

Creates an IpAddr::V4 from a four element byte array.

§Examples
use std:🥅:{IpAddr, Ipv4Addr};

let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);

1.9.0 · Source§

Source§

Creates an Ipv4Addr from a four element byte array.

§Examples
use std:🥅:Ipv4Addr;

let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);

1.71.0 · Source§

This trait is implemented for tuples up to twelve items long.

Source§

Converts to this type from the input type.

Source§

Source§

Converts to this type from the input type.

Source§

Source§

Converts to this type from the input type.

1.0.0 · Source§

The hash of an array is the same as that of the corresponding slice, as required by the Borrow implementation.

use std::hash::BuildHasher;

let b = std::hash::RandomState::new();
let a: [u8; 3] = [0xa8, 0x3c, 0x09];
let s: &[u8] = &[0xa8, 0x3c, 0x09];
assert_eq!(b.hash_one(a), b.hash_one(s));

1.50.0 · Source§

Source§

The returned type after indexing.

Source§

Performs the indexing (container[index]) operation. Read more

1.50.0 · Source§

1.0.0 · Source§

Source§

The type of the elements being iterated over.

Source§

Which kind of iterator are we turning this into?

Source§

Creates an iterator from a value. Read more

1.0.0 · Source§

Source§

The type of the elements being iterated over.

Source§

Which kind of iterator are we turning this into?

Source§

Creates an iterator from a value. Read more

1.53.0 · Source§

Source§

Creates a consuming iterator, that is, one that moves each value out of the array (from start to end).

The array cannot be used after calling this unless T implementsCopy, so the whole array is copied.

Arrays have special behavior when calling .into_iter() prior to the 2021 edition – see the array Editions section for more information.

Source§

The type of the elements being iterated over.

Source§

Which kind of iterator are we turning this into?

1.0.0 · Source§

1.0.0 · Source§

Source§

Tests for self and other values to be equal, and is used by ==.

Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Source§

Source§

Tests for self and other values to be equal, and is used by ==.

1.0.0 · Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

1.0.0 · Source§

Source§

Tests for self and other values to be equal, and is used by ==.

Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

1.0.0 · Source§

Source§

Tests for self and other values to be equal, and is used by ==.

Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

1.0.0 · Source§

Source§

Tests for self and other values to be equal, and is used by ==.

Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

1.0.0 · Source§

Source§

Tests for self and other values to be equal, and is used by ==.

Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

1.0.0 · Source§

Source§

Tests for self and other values to be equal, and is used by ==.

Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

1.0.0 · Source§

Source§

Tests for self and other values to be equal, and is used by ==.

Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Source§

Source§

Tests for self and other values to be equal, and is used by ==.

1.0.0 · Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Source§

Source§

Tests for self and other values to be equal, and is used by ==.

1.0.0 · Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Source§

Source§

Tests for self and other values to be equal, and is used by ==.

1.0.0 · Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

1.0.0 · Source§

Source§

This method returns an ordering between self and other values if one exists. Read more

Source§

Tests less than (for self and other) and is used by the < operator. Read more

Source§

Tests less than or equal to (for self and other) and is used by the<= operator. Read more

Source§

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Source§

Tests greater than (for self and other) and is used by the >operator. Read more

Source§

Searches for chars that are equal to any of the chars in the array.

§Examples

assert_eq!("Hello world".find(&['o', 'l']), Some(2));
assert_eq!("Hello world".find(&['h', 'w']), Some(6));

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Associated searcher for this pattern

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Constructs the associated searcher fromself and the haystack to search in.

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Checks whether the pattern matches anywhere in the haystack

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Checks whether the pattern matches at the front of the haystack

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Removes the pattern from the front of haystack, if it matches.

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Checks whether the pattern matches at the back of the haystack

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Removes the pattern from the back of haystack, if it matches.

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Returns the pattern as utf-8 bytes if possible.

Source§

Searches for chars that are equal to any of the chars in the array.

§Examples

assert_eq!("Hello world".find(['o', 'l']), Some(2));
assert_eq!("Hello world".find(['h', 'w']), Some(6));

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Associated searcher for this pattern

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Constructs the associated searcher fromself and the haystack to search in.

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Checks whether the pattern matches anywhere in the haystack

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Checks whether the pattern matches at the front of the haystack

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Removes the pattern from the front of haystack, if it matches.

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Checks whether the pattern matches at the back of the haystack

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Removes the pattern from the back of haystack, if it matches.

Source§

🔬This is a nightly-only experimental API. (pattern #27721)

Returns the pattern as utf-8 bytes if possible.

1.51.0 · Source§

Source§

🔬This is a nightly-only experimental API. (slice_pattern #56345)

The element type of the slice being matched on.

Source§

🔬This is a nightly-only experimental API. (slice_pattern #56345)

Currently, the consumers of SlicePattern need a slice.

1.34.0 · Source§

Tries to create an array ref &[T; N] from a slice ref &[T]. Succeeds ifslice.len() == N.

let bytes: [u8; 3] = [1, 0, 2];

let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(*bytes_head));

let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(*bytes_tail));

Source§

The type returned in the event of a conversion error.

Source§

Performs the conversion.

1.34.0 · Source§

Tries to create an array [T; N] by copying from a slice &[T]. Succeeds if slice.len() == N.

let bytes: [u8; 3] = [1, 0, 2];

let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(bytes_head));

let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(bytes_tail));

Source§

The type returned in the event of a conversion error.

Source§

Performs the conversion.

1.34.0 · Source§

Tries to create a mutable array ref &mut [T; N] from a mutable slice ref&mut [T]. Succeeds if slice.len() == N.

let mut bytes: [u8; 3] = [1, 0, 2];

let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(*bytes_head));

let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(*bytes_tail));

Source§

The type returned in the event of a conversion error.

Source§

Performs the conversion.

1.59.0 · Source§

Tries to create an array [T; N] by copying from a mutable slice &mut [T]. Succeeds if slice.len() == N.

let mut bytes: [u8; 3] = [1, 0, 2];

let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(bytes_head));

let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(bytes_tail));

Source§

The type returned in the event of a conversion error.

Source§

Performs the conversion.

Source§

1.58.0 · Source§

1.0.0 · Source§

Source§

Source§