Primitive Typearray
Expand description
A fixed-size array, denoted[T; N], for the element type,T, and thenon-negative compile-time constant size,N.
There are two syntactic forms for creating an array:
A list with each element, i.e.,
[x, y, z].A repeat expression
[expr; N]whereNis how many times to repeatexprin the array.exprmust either be:- A value of a type implementing the
Copytrait - A
constvalue
- A value of a type implementing the
Note that[expr; 0] is allowed, and produces an empty array.This will still evaluateexpr, however, and immediately drop the resulting value, sobe mindful of side effects.
Arrays ofany size implement the following traits if the element type allows it:
CopyCloneDebugIntoIterator(implemented for[T; N],&[T; N]and&mut [T; N])PartialEq,PartialOrd,Eq,OrdHashAsRef,AsMutBorrow,BorrowMut
Arrays of sizes from 0 to 32 (inclusive) implement theDefault traitif the element type allows it. As a stopgap, trait implementations arestatically generated up to size 32.
Arrays of sizes from 1 to 12 (inclusive) implementFrom<Tuple>, whereTupleis a homogeneoustuple of appropriate length.
Arrays coerce toslices ([T]), so a slice method may be called onan 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’stry_from(slice) implementations (and the correspondingslice.try_into()array implementations) succeed if the input slice length is the same as the resultarray length. They optimize especially well when the optimizer can easily determinethe slice length, e.g.<[u8; 4]>::try_from(&slice[4..8]).unwrap(). Array implementsTryFrom returning:
[T; N]copies from the slice’s elements&[T; N]references the original slice’s elements&mut [T; N]references the original slice’s elements
You can move elements out of an array with aslice pattern. If you wantone element, seemem::replace.
§Examples
letmutarray: [i32;3] = [0;3];array[1] =1;array[2] =2;assert_eq!([1,2],&array[1..]);// This loop prints: 0 1 2forxinarray {print!("{x} ");}You can also iterate over reference to the array’s elements:
You can use<ArrayType>::try_from(slice) orslice.try_into() to get an array froma slice:
letbytes: [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 aslice pattern to move elements out of an array:
fnmove_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:
§Editions
Prior to Rust 1.53, arrays did not implementIntoIterator by value, so the method callarray.into_iter() auto-referenced into aslice iterator. Right now, the oldbehavior 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 editionmight be made consistent to the behavior of later editions.
// Rust 2015 and 2018:letarray: [i32;3] = [0;3];// This creates a slice iterator, producing references to each value.foriteminarray.into_iter().enumerate() {let(i, x): (usize,&i32) = item;println!("array[{i}] = {x}");}// The `array_into_iter` lint suggests this change for future compatibility:foriteminarray.iter().enumerate() {let(i, x): (usize,&i32) = item;println!("array[{i}] = {x}");}// You can explicitly iterate an array by value using `IntoIterator::into_iter`foriteminIntoIterator::into_iter(array).enumerate() {let(i, x): (usize, i32) = item;println!("array[{i}] = {x}");}Starting in the 2021 edition,array.into_iter() usesIntoIterator normally to iterateby value, anditer() should be used to iterate by reference like previous editions.
// Rust 2021:letarray: [i32;3] = [0;3];// This iterates by reference:foriteminarray.iter().enumerate() {let(i, x): (usize,&i32) = item;println!("array[{i}] = {x}");}// This iterates by value:foriteminarray.into_iter().enumerate() {let(i, x): (usize, i32) = item;println!("array[{i}] = {x}");}Future language versions might start treating thearray.into_iter()syntax on editions 2015 and 2018 the same as on edition 2021. So code usingthose older editions should still be written with this change in mind, toprevent breakage in the future. The safest way to accomplish this is toavoid theinto_iter syntax on those editions. If an edition update is notviable/desired, there are multiple alternatives:
- use
iter, equivalent to the old behavior, creating references - use
IntoIterator::into_iter, equivalent to the post-2021 behavior (Rust 1.53+) - replace
for ... in array.into_iter() {withfor ... in array {,equivalent to the post-2021 behavior (Rust 1.53+)
// Rust 2015 and 2018:letarray: [i32;3] = [0;3];// This iterates by reference:foriteminarray.iter() {letx:&i32 = item;println!("{x}");}// This iterates by value:foriteminIntoIterator::into_iter(array) {letx: i32 = item;println!("{x}");}// This iterates by value:foriteminarray {letx: i32 = item;println!("{x}");}// IntoIter can also start a chain.// This iterates by value:foriteminIntoIterator::into_iter(array).enumerate() {let(i, x): (usize, i32) = item;println!("array[{i}] = {x}");}Implementations§
Source§impl<T, const N:usize> [MaybeUninit<T>;N]
impl<T, const N:usize> [MaybeUninit<T>;N]
Source§impl<const N:usize> [u8;N]
impl<const N:usize> [u8;N]
Sourcepub const fnas_ascii(&self) ->Option<&[AsciiChar;N]>
🔬This is a nightly-only experimental API. (ascii_char #110998)
pub const fnas_ascii(&self) ->Option<&[AsciiChar;N]>
ascii_char #110998)Converts this array of bytes into an array of ASCII characters,or returnsNone if any of the characters is non-ASCII.
§Examples
Sourcepub const unsafe fnas_ascii_unchecked(&self) -> &[AsciiChar;N]
🔬This is a nightly-only experimental API. (ascii_char #110998)
pub const unsafe fnas_ascii_unchecked(&self) -> &[AsciiChar;N]
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 in0..=127, or else this is UB.
Source§impl<T, const N:usize>[T; N]
impl<T, const N:usize>[T; N]
1.55.0 (const:unstable) ·Sourcepub fnmap<F, U>(self, f: F) ->[U; N]where F:FnMut(T) -> U,
pub fnmap<F, U>(self, f: F) ->[U; N]where F:FnMut(T) -> U,
Returns an array of the same size asself, with functionf applied to each elementin 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 optimizedas well as they could be. This mainly concerns large arrays, as mappingover small arrays seem to be optimized just fine. Also note that indebug mode (i.e. without any optimizations), this method can use a lotof stack space (a few times the size of the array or more).
Therefore, in performance-critical code, try to avoid using this methodon large arrays or check the emitted code. Also try to avoid chainedmaps (e.g.arr.map(...).map(...)).
In many cases, you can instead useIterator::map by calling.iter()or.into_iter() on your array.[T; N]::map is only necessary if youreally need a new array of the same size as the result. Rust’s lazyiterators tend to get optimized very well.
§Examples
Sourcepub const fntry_map<R>( self, f: implFnMut(T) -> R,) -> <<R asTry>::Residual asResidual<[<R asTry>::Output;N]>>::TryType
🔬This is a nightly-only experimental API. (array_try_map #79711)
pub const fntry_map<R>( self, f: implFnMut(T) -> R,) -> <<R asTry>::Residual asResidual<[<R asTry>::Output;N]>>::TryType
array_try_map #79711)A fallible functionf applied to each element on arrayself in order toreturn an array the same size asself or the first error encountered.
The return type of this function depends on the return type of the closure.If you returnResult<T, E> from the closure, you’ll get aResult<[T; N], E>.If you returnOption<T> from the closure, you’ll get anOption<[T; N]>.
§Examples
#![feature(array_try_map)]leta = ["1","2","3"];letb = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v +1);assert_eq!(b, [2,3,4]);leta = ["1","2a","3"];letb = a.try_map(|v| v.parse::<u32>());assert!(b.is_err());usestd::num::NonZero;letz = [1,2,0,3,4];assert_eq!(z.try_map(NonZero::new),None);leta = [1,2,3];letb = a.try_map(NonZero::new);letc = b.map(|x| x.map(NonZero::get));assert_eq!(c,Some(a));1.57.0 (const: 1.57.0) ·Sourcepub const fnas_slice(&self) -> &[T]
pub const fnas_slice(&self) -> &[T]
Returns a slice containing the entire array. Equivalent to&s[..].
1.57.0 (const: 1.89.0) ·Sourcepub const fnas_mut_slice(&mut self) -> &mut[T]
pub const fnas_mut_slice(&mut self) -> &mut[T]
Returns a mutable slice containing the entire array. Equivalent to&mut s[..].
1.77.0 (const: 1.91.0) ·Sourcepub const fneach_ref(&self) -> [&T;N]
pub const fneach_ref(&self) -> [&T;N]
Borrows each element and returns an array of references with the samesize asself.
§Example
letfloats = [3.1,2.7, -1.0];letfloat_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 originalarray if its elements are notCopy.
1.77.0 (const: 1.91.0) ·Sourcepub const fneach_mut(&mut self) -> [&mut T;N]
pub const fneach_mut(&mut self) -> [&mut T;N]
Borrows each element mutably and returns an array of mutable referenceswith the same size asself.
§Example
Sourcepub fnsplit_array_ref<const M:usize>(&self) -> (&[T; M], &[T])
🔬This is a nightly-only experimental API. (split_array #90091)
pub fnsplit_array_ref<const M:usize>(&self) -> (&[T; M], &[T])
split_array #90091)Divides one array reference into two at an index.
The first will contain all indices from[0, M) (excludingthe indexM itself) and the second will contain allindices from[M, N) (excluding the indexN itself).
§Panics
Panics ifM > N.
§Examples
#![feature(split_array)]letv = [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,&[]);}Sourcepub fnsplit_array_mut<const M:usize>(&mut self) -> (&mut[T; M], &mut[T])
🔬This is a nightly-only experimental API. (split_array #90091)
pub fnsplit_array_mut<const M:usize>(&mut self) -> (&mut[T; M], &mut[T])
split_array #90091)Sourcepub fnrsplit_array_ref<const M:usize>(&self) -> (&[T], &[T; M])
🔬This is a nightly-only experimental API. (split_array #90091)
pub fnrsplit_array_ref<const M:usize>(&self) -> (&[T], &[T; M])
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) (excludingthe indexN - M itself) and the second will contain allindices from[N - M, N) (excluding the indexN itself).
§Panics
Panics ifM > N.
§Examples
#![feature(split_array)]letv = [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]);}Sourcepub fnrsplit_array_mut<const M:usize>(&mut self) -> (&mut[T], &mut[T; M])
🔬This is a nightly-only experimental API. (split_array #90091)
pub fnrsplit_array_mut<const M:usize>(&mut self) -> (&mut[T], &mut[T; M])
split_array #90091)Trait Implementations§
1.4.0 (const:unstable) ·Source§impl<T, const N:usize>BorrowMut<[T]> for[T; N]
impl<T, const N:usize>BorrowMut<[T]> for[T; N]
Source§fnborrow_mut(&mut self) -> &mut[T]
fnborrow_mut(&mut self) -> &mut[T]
1.56.0 ·Source§impl<K, V, const N:usize>From<[(K, V);N]> forBTreeMap<K, V>where K:Ord,
impl<K, V, const N:usize>From<[(K, V);N]> forBTreeMap<K, V>where K:Ord,
1.56.0 ·Source§impl<K, V, const N:usize>From<[(K, V);N]> forHashMap<K, V,RandomState>
impl<K, V, const N:usize>From<[(K, V);N]> forHashMap<K, V,RandomState>
1.71.0 ·Source§impl<T>From<[T; N]> for(T₁, T₂, …, Tₙ)
This trait is implemented for tuples up to twelve items long.
impl<T>From<[T; N]> for(T₁, T₂, …, Tₙ)
This trait is implemented for tuples up to twelve items long.
1.56.0 ·Source§impl<T, const N:usize>From<[T; N]> forBinaryHeap<T>where T:Ord,
impl<T, const N:usize>From<[T; N]> forBinaryHeap<T>where T:Ord,
Source§fnfrom(arr:[T; N]) ->BinaryHeap<T>
fnfrom(arr:[T; N]) ->BinaryHeap<T>
1.56.0 ·Source§impl<T, const N:usize>From<[T; N]> forLinkedList<T>
impl<T, const N:usize>From<[T; N]> forLinkedList<T>
Source§fnfrom(arr:[T; N]) ->LinkedList<T>
fnfrom(arr:[T; N]) ->LinkedList<T>
1.17.0 (const:unstable) ·Source§implFrom<[u16;8]> forIpAddr
implFrom<[u16;8]> forIpAddr
1.16.0 (const:unstable) ·Source§implFrom<[u16;8]> forIpv6Addr
implFrom<[u16;8]> forIpv6Addr
1.17.0 (const:unstable) ·Source§implFrom<[u8;16]> forIpAddr
implFrom<[u8;16]> forIpAddr
1.9.0 (const:unstable) ·Source§implFrom<[u8;16]> forIpv6Addr
implFrom<[u8;16]> forIpv6Addr
1.71.0 ·Source§impl<T>From<(T₁, T₂, …, Tₙ)> for[T; N]
This trait is implemented for tuples up to twelve items long.
impl<T>From<(T₁, T₂, …, Tₙ)> for[T; N]
This trait is implemented for tuples up to twelve items long.
1.0.0 ·Source§impl<T, const N:usize>Hash for[T; N]where T:Hash,
The hash of an array is the same as that of the corresponding slice,as required by theBorrow implementation.
impl<T, const N:usize>Hash for[T; N]where T:Hash,
The hash of an array is the same as that of the corresponding slice,as required by theBorrow implementation.
1.0.0 ·Source§impl<'a, T, const N:usize>IntoIterator for &'a[T; N]
impl<'a, T, const N:usize>IntoIterator for &'a[T; N]
1.0.0 ·Source§impl<'a, T, const N:usize>IntoIterator for &'a mut[T; N]
impl<'a, T, const N:usize>IntoIterator for &'a mut[T; N]
1.53.0 ·Source§impl<T, const N:usize>IntoIterator for[T; N]
impl<T, const N:usize>IntoIterator for[T; N]
Source§fninto_iter(self) -> <[T; N] asIntoIterator>::IntoIter
fninto_iter(self) -> <[T; N] asIntoIterator>::IntoIter
Creates a consuming iterator, that is, one that moves each value out ofthe array (from start to end).
The array cannot be used after calling this unlessT implementsCopy, so the whole array is copied.
Arrays have special behavior when calling.into_iter() prior to the2021 edition – see thearray Editions section for more information.
1.0.0 ·Source§impl<T, const N:usize>Ord for[T; N]where T:Ord,
Implements comparison of arrayslexicographically.
impl<T, const N:usize>Ord for[T; N]where T:Ord,
Implements comparison of arrayslexicographically.
1.0.0 (const:unstable) ·Source§impl<T, U, const N:usize>PartialEq<&[U]> for[T; N]where T:PartialEq<U>,
impl<T, U, const N:usize>PartialEq<&[U]> for[T; N]where T:PartialEq<U>,
1.0.0 (const:unstable) ·Source§impl<T, U, const N:usize>PartialEq<&mut[U]> for[T; N]where T:PartialEq<U>,
impl<T, U, const N:usize>PartialEq<&mut[U]> for[T; N]where T:PartialEq<U>,
1.0.0 (const:unstable) ·Source§impl<T, U, const N:usize>PartialEq<[U]> for[T; N]where T:PartialEq<U>,
impl<T, U, const N:usize>PartialEq<[U]> for[T; N]where T:PartialEq<U>,
1.0.0 (const:unstable) ·Source§impl<T, U, const N:usize>PartialEq<[U; N]> for &[T]where T:PartialEq<U>,
impl<T, U, const N:usize>PartialEq<[U; N]> for &[T]where T:PartialEq<U>,
1.0.0 (const:unstable) ·Source§impl<T, U, const N:usize>PartialEq<[U; N]> for &mut[T]where T:PartialEq<U>,
impl<T, U, const N:usize>PartialEq<[U; N]> for &mut[T]where T:PartialEq<U>,
1.0.0 (const:unstable) ·Source§impl<T, U, const N:usize>PartialEq<[U; N]> for[T]where T:PartialEq<U>,
impl<T, U, const N:usize>PartialEq<[U; N]> for[T]where T:PartialEq<U>,
1.0.0 (const:unstable) ·Source§impl<T, U, const N:usize>PartialEq<[U; N]> for[T; N]where T:PartialEq<U>,
impl<T, U, const N:usize>PartialEq<[U; N]> for[T; N]where T:PartialEq<U>,
1.0.0 ·Source§impl<T, const N:usize>PartialOrd for[T; N]where T:PartialOrd,
Implements comparison of arrayslexicographically.
impl<T, const N:usize>PartialOrd for[T; N]where T:PartialOrd,
Implements comparison of arrayslexicographically.
Source§impl<'b, const N:usize>Pattern for &'b [char;N]
Searches for chars that are equal to any of thechars in the array.
impl<'b, const N:usize>Pattern for &'b [char;N]
Searches for chars that are equal to any of thechars in the array.
§Examples
Source§typeSearcher<'a> =CharArrayRefSearcher<'a, 'b, N>
typeSearcher<'a> =CharArrayRefSearcher<'a, 'b, N>
pattern #27721)Source§fninto_searcher<'a>(self, haystack: &'astr) ->CharArrayRefSearcher<'a, 'b, N>
fninto_searcher<'a>(self, haystack: &'astr) ->CharArrayRefSearcher<'a, 'b, N>
pattern #27721)self and thehaystack to search in.Source§fnis_contained_in<'a>(self, haystack: &'astr) ->bool
fnis_contained_in<'a>(self, haystack: &'astr) ->bool
pattern #27721)Source§fnis_prefix_of<'a>(self, haystack: &'astr) ->bool
fnis_prefix_of<'a>(self, haystack: &'astr) ->bool
pattern #27721)Source§fnstrip_prefix_of<'a>(self, haystack: &'astr) ->Option<&'astr>
fnstrip_prefix_of<'a>(self, haystack: &'astr) ->Option<&'astr>
pattern #27721)Source§fnis_suffix_of<'a>(self, haystack: &'astr) ->boolwhereCharArrayRefSearcher<'a, 'b, N>:ReverseSearcher<'a>,
fnis_suffix_of<'a>(self, haystack: &'astr) ->boolwhereCharArrayRefSearcher<'a, 'b, N>:ReverseSearcher<'a>,
pattern #27721)Source§fnstrip_suffix_of<'a>(self, haystack: &'astr) ->Option<&'astr>whereCharArrayRefSearcher<'a, 'b, N>:ReverseSearcher<'a>,
fnstrip_suffix_of<'a>(self, haystack: &'astr) ->Option<&'astr>whereCharArrayRefSearcher<'a, 'b, N>:ReverseSearcher<'a>,
pattern #27721)Source§fnas_utf8_pattern(&self) ->Option<Utf8Pattern<'_>>
fnas_utf8_pattern(&self) ->Option<Utf8Pattern<'_>>
pattern #27721)Source§impl<const N:usize>Pattern for [char;N]
Searches for chars that are equal to any of thechars in the array.
impl<const N:usize>Pattern for [char;N]
Searches for chars that are equal to any of thechars in the array.
§Examples
Source§typeSearcher<'a> =CharArraySearcher<'a, N>
typeSearcher<'a> =CharArraySearcher<'a, N>
pattern #27721)Source§fninto_searcher<'a>(self, haystack: &'astr) ->CharArraySearcher<'a, N>
fninto_searcher<'a>(self, haystack: &'astr) ->CharArraySearcher<'a, N>
pattern #27721)self and thehaystack to search in.Source§fnis_contained_in<'a>(self, haystack: &'astr) ->bool
fnis_contained_in<'a>(self, haystack: &'astr) ->bool
pattern #27721)Source§fnis_prefix_of<'a>(self, haystack: &'astr) ->bool
fnis_prefix_of<'a>(self, haystack: &'astr) ->bool
pattern #27721)Source§fnstrip_prefix_of<'a>(self, haystack: &'astr) ->Option<&'astr>
fnstrip_prefix_of<'a>(self, haystack: &'astr) ->Option<&'astr>
pattern #27721)Source§fnis_suffix_of<'a>(self, haystack: &'astr) ->boolwhereCharArraySearcher<'a, N>:ReverseSearcher<'a>,
fnis_suffix_of<'a>(self, haystack: &'astr) ->boolwhereCharArraySearcher<'a, N>:ReverseSearcher<'a>,
pattern #27721)Source§fnstrip_suffix_of<'a>(self, haystack: &'astr) ->Option<&'astr>whereCharArraySearcher<'a, N>:ReverseSearcher<'a>,
fnstrip_suffix_of<'a>(self, haystack: &'astr) ->Option<&'astr>whereCharArraySearcher<'a, N>:ReverseSearcher<'a>,
pattern #27721)Source§fnas_utf8_pattern(&self) ->Option<Utf8Pattern<'_>>
fnas_utf8_pattern(&self) ->Option<Utf8Pattern<'_>>
pattern #27721)1.51.0 ·Source§impl<T, const N:usize>SlicePattern for[T; N]
impl<T, const N:usize>SlicePattern for[T; N]
1.34.0 (const:unstable) ·Source§impl<'a, T, const N:usize>TryFrom<&'a[T]> for &'a[T; N]
Tries to create an array ref&[T; N] from a slice ref&[T]. Succeeds ifslice.len() == N.
impl<'a, T, const N:usize>TryFrom<&'a[T]> for &'a[T; N]
Tries to create an array ref&[T; N] from a slice ref&[T]. Succeeds ifslice.len() == N.
1.34.0 (const:unstable) ·Source§impl<T, const N:usize>TryFrom<&[T]> for[T; N]where T:Copy,
Tries to create an array[T; N] by copying from a slice&[T].Succeeds ifslice.len() == N.
impl<T, const N:usize>TryFrom<&[T]> for[T; N]where T:Copy,
Tries to create an array[T; N] by copying from a slice&[T].Succeeds ifslice.len() == N.
1.34.0 (const:unstable) ·Source§impl<'a, T, const N:usize>TryFrom<&'a mut[T]> for &'a mut[T; N]
Tries to create a mutable array ref&mut [T; N] from a mutable slice ref&mut [T]. Succeeds ifslice.len() == N.
impl<'a, T, const N:usize>TryFrom<&'a mut[T]> for &'a mut[T; N]
Tries to create a mutable array ref&mut [T; N] from a mutable slice ref&mut [T]. Succeeds ifslice.len() == N.
1.59.0 (const:unstable) ·Source§impl<T, const N:usize>TryFrom<&mut[T]> for[T; N]where T:Copy,
Tries to create an array[T; N] by copying from a mutable slice&mut [T].Succeeds ifslice.len() == N.
impl<T, const N:usize>TryFrom<&mut[T]> for[T; N]where T:Copy,
Tries to create an array[T; N] by copying from a mutable slice&mut [T].Succeeds ifslice.len() == N.
1.43.0 ·Source§impl<T, const N:usize>TryFrom<Box<[T]>> forBox<[T; N]>
impl<T, const N:usize>TryFrom<Box<[T]>> forBox<[T; N]>
Source§fntry_from( boxed_slice:Box<[T]>,) ->Result<Box<[T; N]>, <Box<[T; N]> asTryFrom<Box<[T]>>>::Error>
fntry_from( boxed_slice:Box<[T]>,) ->Result<Box<[T; N]>, <Box<[T; N]> asTryFrom<Box<[T]>>>::Error>
Attempts to convert aBox<[T]> into aBox<[T; N]>.
The conversion occurs in-place and does not require anew memory allocation.
§Errors
Returns the oldBox<[T]> in theErr variant ifboxed_slice.len() does not equalN.
1.66.0 ·Source§impl<T, const N:usize>TryFrom<Vec<T>> forBox<[T; N]>
impl<T, const N:usize>TryFrom<Vec<T>> forBox<[T; N]>
Source§fntry_from( vec:Vec<T>,) ->Result<Box<[T; N]>, <Box<[T; N]> asTryFrom<Vec<T>>>::Error>
fntry_from( vec:Vec<T>,) ->Result<Box<[T; N]>, <Box<[T; N]> asTryFrom<Vec<T>>>::Error>
Attempts to convert aVec<T> into aBox<[T; N]>.
LikeVec::into_boxed_slice, this is in-place ifvec.capacity() == N,but will require a reallocation otherwise.
§Errors
Returns the originalVec<T> in theErr variant ifboxed_slice.len() does not equalN.
§Examples
This can be used withvec! to create an array on the heap:
1.48.0 ·Source§impl<T, A, const N:usize>TryFrom<Vec<T, A>> for[T; N]where A:Allocator,
impl<T, A, const N:usize>TryFrom<Vec<T, A>> for[T; N]where A:Allocator,
Source§fntry_from(vec:Vec<T, A>) ->Result<[T; N],Vec<T, A>>
fntry_from(vec:Vec<T, A>) ->Result<[T; N],Vec<T, A>>
Gets the entire contents of theVec<T> as an array,if its size exactly matches that of the requested array.
§Examples
If the length doesn’t match, the input comes back inErr:
letr:Result<[i32;4],_> = (0..10).collect::<Vec<_>>().try_into();assert_eq!(r,Err(vec![0,1,2,3,4,5,6,7,8,9]));If you’re fine with just getting a prefix of theVec<T>,you can call.truncate(N) first.