Movatterモバイル変換


[0]ホーム

URL:


array

Primitive Typearray 

1.0.0
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] whereN is how many times to repeatexpr in the array.expr must either be:

    • A value of a type implementing theCopy trait
    • Aconst value

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:

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:

letarray: [i32;3] = [0;3];forxin&array { }

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:

lettuple: (u32, u32, u32) = (1,2,3);letarray: [u32;3] = tuple.into();

§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:

  • useiter, equivalent to the old behavior, creating references
  • useIntoIterator::into_iter, equivalent to the post-2021 behavior (Rust 1.53+)
  • replacefor ... 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]

Source

pub const fntranspose(self) ->MaybeUninit<[T; N]>

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

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

§Examples
#![feature(maybe_uninit_uninit_array_transpose)]letdata = [MaybeUninit::<u8>::uninit();1000];letdata: MaybeUninit<[u8;1000]> = data.transpose();
Source§

impl<const N:usize> [u8;N]

Source

pub const fnas_ascii(&self) ->Option<&[AsciiChar;N]>

🔬This is a nightly-only experimental API. (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
#![feature(ascii_char)]constHEX_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

pub const unsafe fnas_ascii_unchecked(&self) -> &[AsciiChar;N]

🔬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 in0..=127, or else this is UB.

Source§

impl<T, const N:usize>[T; N]

1.55.0 (const:unstable) ·Source

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
letx = [1,2,3];lety = x.map(|v| v +1);assert_eq!(y, [2,3,4]);letx = [1,2,3];letmuttemp =0;lety = x.map(|v| { temp +=1; v * temp });assert_eq!(y, [1,4,9]);letx = ["Ferris","Bueller's","Day","Off"];lety = x.map(|v| v.len());assert_eq!(y, [6,9,3,3]);
Source

pub const fntry_map<R>( self, f: implFnMut(T) -> R,) -> <<R asTry>::Residual asResidual<[<R asTry>::Output;N]>>::TryType
where R:Try, <R asTry>::Residual:Residual<[<R asTry>::Output;N]>,

🔬This is a nightly-only experimental API. (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) ·Source

pub const fnas_slice(&self) -> &[T]

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

1.57.0 (const: 1.89.0) ·Source

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) ·Source

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.

letstrings = ["Ferris".to_string(),"♥".to_string(),"Rust".to_string()];letis_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: 1.91.0) ·Source

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
letmutfloats = [3.1,2.7, -1.0];letfloat_refs: [&mutf64;3] = floats.each_mut();*float_refs[0] =0.0;assert_eq!(float_refs, [&mut0.0,&mut2.7,&mut-1.0]);assert_eq!(floats, [0.0,2.7, -1.0]);
Source

pub fnsplit_array_ref<const M:usize>(&self) -> (&[T; M], &[T])

🔬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) (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,&[]);}
Source

pub fnsplit_array_mut<const M:usize>(&mut self) -> (&mut[T; M], &mut[T])

🔬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) (excludingthe indexM itself) and the second will contain allindices from[M, N) (excluding the indexN itself).

§Panics

Panics ifM > N.

§Examples
#![feature(split_array)]letmutv = [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

pub fnrsplit_array_ref<const M:usize>(&self) -> (&[T], &[T; M])

🔬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) (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]);}
Source

pub fnrsplit_array_mut<const M:usize>(&mut self) -> (&mut[T], &mut[T; M])

🔬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) (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)]letmutv = [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§

impl<T, const N:usize> [Option<T>;N]

Source

pub fntranspose(self) ->Option<[T; N]>

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

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

§Examples
#![feature(option_array_transpose)]letdata = [Some(0);1000];letdata:Option<[u8;1000]> = data.transpose();assert_eq!(data,Some([0;1000]));letdata = [Some(0),None];letdata:Option<[u8;2]> = data.transpose();assert_eq!(data,None);

Trait Implementations§

1.0.0 (const:unstable) ·Source§

impl<T, const N:usize>AsMut<[T]> for[T; N]

Source§

fnas_mut(&mut self) -> &mut[T]

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

impl<T, const N:usize>AsMut<[T; N]> forSimd<T, N>

Source§

fnas_mut(&mut self) -> &mut[T; N]

Converts this type into a mutable reference of the (usually inferred) input type.
1.0.0 (const:unstable) ·Source§

impl<T, const N:usize>AsRef<[T]> for[T; N]

Source§

fnas_ref(&self) -> &[T]

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

impl<T, const N:usize>AsRef<[T; N]> forSimd<T, N>

Source§

fnas_ref(&self) -> &[T; N]

Converts this type into a shared reference of the (usually inferred) input type.
1.4.0 (const:unstable) ·Source§

impl<T, const N:usize>Borrow<[T]> for[T; N]

Source§

fnborrow(&self) -> &[T]

Immutably borrows from an owned value.Read more
1.4.0 (const:unstable) ·Source§

impl<T, const N:usize>BorrowMut<[T]> for[T; N]

Source§

fnborrow_mut(&mut self) -> &mut[T]

Mutably borrows from an owned value.Read more
1.58.0 ·Source§

impl<T, const N:usize>Clone for[T; N]
where T:Clone,

Source§

fnclone(&self) ->[T; N]

Returns a duplicate of the value.Read more
Source§

fnclone_from(&mut self, other: &[T; N])

Performs copy-assignment fromsource.Read more
1.0.0 ·Source§

impl<T, const N:usize>Debug for[T; N]
where T:Debug,

Source§

fnfmt(&self, f: &mutFormatter<'_>) ->Result<(),Error>

Formats the value using the given formatter.Read more
1.4.0 ·Source§

impl<T>Default for[T; 32]
where T:Default,

Source§

fndefault() ->[T; 32]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 31]
where T:Default,

Source§

fndefault() ->[T; 31]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 30]
where T:Default,

Source§

fndefault() ->[T; 30]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 29]
where T:Default,

Source§

fndefault() ->[T; 29]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 28]
where T:Default,

Source§

fndefault() ->[T; 28]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 27]
where T:Default,

Source§

fndefault() ->[T; 27]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 26]
where T:Default,

Source§

fndefault() ->[T; 26]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 25]
where T:Default,

Source§

fndefault() ->[T; 25]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 24]
where T:Default,

Source§

fndefault() ->[T; 24]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 23]
where T:Default,

Source§

fndefault() ->[T; 23]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 22]
where T:Default,

Source§

fndefault() ->[T; 22]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 21]
where T:Default,

Source§

fndefault() ->[T; 21]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 20]
where T:Default,

Source§

fndefault() ->[T; 20]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 19]
where T:Default,

Source§

fndefault() ->[T; 19]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 18]
where T:Default,

Source§

fndefault() ->[T; 18]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 17]
where T:Default,

Source§

fndefault() ->[T; 17]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 16]
where T:Default,

Source§

fndefault() ->[T; 16]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 15]
where T:Default,

Source§

fndefault() ->[T; 15]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 14]
where T:Default,

Source§

fndefault() ->[T; 14]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 13]
where T:Default,

Source§

fndefault() ->[T; 13]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 12]
where T:Default,

Source§

fndefault() ->[T; 12]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 11]
where T:Default,

Source§

fndefault() ->[T; 11]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 10]
where T:Default,

Source§

fndefault() ->[T; 10]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 9]
where T:Default,

Source§

fndefault() ->[T; 9]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 8]
where T:Default,

Source§

fndefault() ->[T; 8]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 7]
where T:Default,

Source§

fndefault() ->[T; 7]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 6]
where T:Default,

Source§

fndefault() ->[T; 6]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 5]
where T:Default,

Source§

fndefault() ->[T; 5]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 4]
where T:Default,

Source§

fndefault() ->[T; 4]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 3]
where T:Default,

Source§

fndefault() ->[T; 3]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 2]
where T:Default,

Source§

fndefault() ->[T; 2]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 1]
where T:Default,

Source§

fndefault() ->[T; 1]

Returns the “default value” for a type.Read more
1.4.0 ·Source§

impl<T>Default for[T; 0]

Source§

fndefault() ->[T; 0]

Returns the “default value” for a type.Read more
1.77.0 ·Source§

impl<'a, T, const N:usize>From<&'a[T; N]> forCow<'a,[T]>
where T:Clone,

Source§

fnfrom(s: &'a[T; N]) ->Cow<'a,[T]>

Creates aBorrowed variant ofCowfrom a reference to an array.

This conversion does not allocate or clone the data.

1.74.0 ·Source§

impl<T, const N:usize>From<&[T; N]> forVec<T>
where T:Clone,

Source§

fnfrom(s: &[T; N]) ->Vec<T>

Allocates aVec<T> and fills it by clonings’s items.

§Examples
assert_eq!(Vec::from(&[1,2,3]),vec![1,2,3]);
1.74.0 ·Source§

impl<T, const N:usize>From<&mut[T; N]> forVec<T>
where T:Clone,

Source§

fnfrom(s: &mut[T; N]) ->Vec<T>

Allocates aVec<T> and fills it by clonings’s items.

§Examples
assert_eq!(Vec::from(&mut[1,2,3]),vec![1,2,3]);
1.56.0 ·Source§

impl<K, V, const N:usize>From<[(K, V);N]> forBTreeMap<K, V>
where K:Ord,

Source§

fnfrom(arr: [(K, V);N]) ->BTreeMap<K, V>

Converts a[(K, V); N] into aBTreeMap<K, V>.

If any entries in the array have equal keys,all but one of the corresponding values will be dropped.

usestd::collections::BTreeMap;letmap1 = BTreeMap::from([(1,2), (3,4)]);letmap2: BTreeMap<_,_> = [(1,2), (3,4)].into();assert_eq!(map1, map2);
1.56.0 ·Source§

impl<K, V, const N:usize>From<[(K, V);N]> forHashMap<K, V,RandomState>
where K:Eq +Hash,

Source§

fnfrom(arr: [(K, V);N]) -> Self

Converts a[(K, V); N] into aHashMap<K, V>.

If any entries in the array have equal keys,all but one of the corresponding values will be dropped.

§Examples
usestd::collections::HashMap;letmap1 = HashMap::from([(1,2), (3,4)]);letmap2: HashMap<_,_> = [(1,2), (3,4)].into();assert_eq!(map1, map2);
1.71.0 ·Source§

impl<T>From<[T; N]> for(T₁, T₂, …, Tₙ)

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

Source§

fnfrom(array:[T; 1]) ->(T,)

Converts to this type from the input type.
1.74.0 ·Source§

impl<T, const N:usize>From<[T; N]> forArc<[T]>

Source§

fnfrom(v:[T; N]) ->Arc<[T]>

Converts a[T; N] into anArc<[T]>.

The conversion moves the array into a newly allocatedArc.

§Example
letoriginal: [i32;3] = [1,2,3];letshared: Arc<[i32]> = Arc::from(original);assert_eq!(&[1,2,3],&shared[..]);
1.56.0 ·Source§

impl<T, const N:usize>From<[T; N]> forBTreeSet<T>
where T:Ord,

Source§

fnfrom(arr:[T; N]) ->BTreeSet<T>

Converts a[T; N] into aBTreeSet<T>.

If the array contains any equal values,all but one will be dropped.

§Examples
usestd::collections::BTreeSet;letset1 = BTreeSet::from([1,2,3,4]);letset2: BTreeSet<_> = [1,2,3,4].into();assert_eq!(set1, set2);
1.56.0 ·Source§

impl<T, const N:usize>From<[T; N]> forBinaryHeap<T>
where T:Ord,

Source§

fnfrom(arr:[T; N]) ->BinaryHeap<T>

usestd::collections::BinaryHeap;letmuth1 = BinaryHeap::from([1,4,2,3]);letmuth2: BinaryHeap<_> = [1,4,2,3].into();while letSome((a, b)) = h1.pop().zip(h2.pop()) {assert_eq!(a, b);}
1.45.0 ·Source§

impl<T, const N:usize>From<[T; N]> forBox<[T]>

Source§

fnfrom(array:[T; N]) ->Box<[T]>

Converts a[T; N] into aBox<[T]>

This conversion moves the array to newly heap-allocated memory.

§Examples
letboxed: Box<[u8]> = Box::from([4,2]);println!("{boxed:?}");
1.56.0 ·Source§

impl<T, const N:usize>From<[T; N]> forHashSet<T,RandomState>
where T:Eq +Hash,

Source§

fnfrom(arr:[T; N]) -> Self

Converts a[T; N] into aHashSet<T>.

If the array contains any equal values,all but one will be dropped.

§Examples
usestd::collections::HashSet;letset1 = HashSet::from([1,2,3,4]);letset2: HashSet<_> = [1,2,3,4].into();assert_eq!(set1, set2);
1.56.0 ·Source§

impl<T, const N:usize>From<[T; N]> forLinkedList<T>

Source§

fnfrom(arr:[T; N]) ->LinkedList<T>

Converts a[T; N] into aLinkedList<T>.

usestd::collections::LinkedList;letlist1 = LinkedList::from([1,2,3,4]);letlist2: LinkedList<_> = [1,2,3,4].into();assert_eq!(list1, list2);
1.74.0 ·Source§

impl<T, const N:usize>From<[T; N]> forRc<[T]>

Source§

fnfrom(v:[T; N]) ->Rc<[T]>

Converts a[T; N] into anRc<[T]>.

The conversion moves the array into a newly allocatedRc.

§Example
letoriginal: [i32;3] = [1,2,3];letshared: Rc<[i32]> = Rc::from(original);assert_eq!(&[1,2,3],&shared[..]);
Source§

impl<T, const N:usize>From<[T; N]> forSimd<T, N>

Source§

fnfrom(array:[T; N]) ->Simd<T, N>

Converts to this type from the input type.
1.44.0 ·Source§

impl<T, const N:usize>From<[T; N]> forVec<T>

Source§

fnfrom(s:[T; N]) ->Vec<T>

Allocates aVec<T> and movess’s items into it.

§Examples
assert_eq!(Vec::from([1,2,3]),vec![1,2,3]);
1.56.0 ·Source§

impl<T, const N:usize>From<[T; N]> forVecDeque<T>

Source§

fnfrom(arr:[T; N]) ->VecDeque<T>

Converts a[T; N] into aVecDeque<T>.

usestd::collections::VecDeque;letdeq1 = VecDeque::from([1,2,3,4]);letdeq2: VecDeque<_> = [1,2,3,4].into();assert_eq!(deq1, deq2);
Source§

impl<T, const N:usize>From<[bool;N]> forMask<T, N>

Source§

fnfrom(array: [bool;N]) ->Mask<T, N>

Converts to this type from the input type.
1.17.0 (const:unstable) ·Source§

implFrom<[u16;8]> forIpAddr

Source§

fnfrom(segments: [u16;8]) ->IpAddr

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

§Examples
usestd::net::{IpAddr, Ipv6Addr};letaddr = 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 (const:unstable) ·Source§

implFrom<[u16;8]> forIpv6Addr

Source§

fnfrom(segments: [u16;8]) ->Ipv6Addr

Creates anIpv6Addr from an eight element 16-bit array.

§Examples
usestd::net::Ipv6Addr;letaddr = 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 (const:unstable) ·Source§

implFrom<[u8;16]> forIpAddr

Source§

fnfrom(octets: [u8;16]) ->IpAddr

Creates anIpAddr::V6 from a sixteen element byte array.

§Examples
usestd::net::{IpAddr, Ipv6Addr};letaddr = 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 (const:unstable) ·Source§

implFrom<[u8;16]> forIpv6Addr

Source§

fnfrom(octets: [u8;16]) ->Ipv6Addr

Creates anIpv6Addr from a sixteen element byte array.

§Examples
usestd::net::Ipv6Addr;letaddr = 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 (const:unstable) ·Source§

implFrom<[u8;4]> forIpAddr

Source§

fnfrom(octets: [u8;4]) ->IpAddr

Creates anIpAddr::V4 from a four element byte array.

§Examples
usestd::net::{IpAddr, Ipv4Addr};letaddr = IpAddr::from([13u8,12u8,11u8,10u8]);assert_eq!(IpAddr::V4(Ipv4Addr::new(13,12,11,10)), addr);
1.9.0 (const:unstable) ·Source§

implFrom<[u8;4]> forIpv4Addr

Source§

fnfrom(octets: [u8;4]) ->Ipv4Addr

Creates anIpv4Addr from a four element byte array.

§Examples
usestd::net::Ipv4Addr;letaddr = Ipv4Addr::from([13u8,12u8,11u8,10u8]);assert_eq!(Ipv4Addr::new(13,12,11,10), addr);
1.71.0 ·Source§

impl<T>From<(T₁, T₂, …, Tₙ)> for[T; N]

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

Source§

fnfrom(tuple:(T,)) ->[T; 1]

Converts to this type from the input type.
Source§

impl<T, const N:usize>From<Mask<T, N>> for [bool;N]

Source§

fnfrom(vector:Mask<T, N>) -> [bool;N]

Converts to this type from the input type.
Source§

impl<T, const N:usize>From<Simd<T, N>> for[T; N]

Source§

fnfrom(vector:Simd<T, N>) ->[T; N]

Converts to this type from the input type.
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.

usestd::hash::BuildHasher;letb = std::hash::RandomState::new();leta: [u8;3] = [0xa8,0x3c,0x09];lets:&[u8] =&[0xa8,0x3c,0x09];assert_eq!(b.hash_one(a), b.hash_one(s));
Source§

fnhash<H>(&self, state:&mut H)
where H:Hasher,

Feeds this value into the givenHasher.Read more
1.3.0 ·Source§

fnhash_slice<H>(data: &[Self], state:&mut H)
where H:Hasher, Self:Sized,

Feeds a slice of this type into the givenHasher.Read more
1.50.0 (const:unstable) ·Source§

impl<T, I, const N:usize>Index<I> for[T; N]
where[T]:Index<I>,

Source§

typeOutput = <[T] asIndex<I>>::Output

The returned type after indexing.
Source§

fnindex(&self, index: I) -> &<[T; N] asIndex<I>>::Output

Performs the indexing (container[index]) operation.Read more
1.50.0 (const:unstable) ·Source§

impl<T, I, const N:usize>IndexMut<I> for[T; N]
where[T]:IndexMut<I>,

Source§

fnindex_mut(&mut self, index: I) -> &mut <[T; N] asIndex<I>>::Output

Performs the mutable indexing (container[index]) operation.Read more
1.0.0 ·Source§

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

Source§

typeItem =&'a T

The type of the elements being iterated over.
Source§

typeIntoIter =Iter<'a, T>

Which kind of iterator are we turning this into?
Source§

fninto_iter(self) ->Iter<'a, T>

Creates an iterator from a value.Read more
1.0.0 ·Source§

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

Source§

typeItem =&'a mut T

The type of the elements being iterated over.
Source§

typeIntoIter =IterMut<'a, T>

Which kind of iterator are we turning this into?
Source§

fninto_iter(self) ->IterMut<'a, T>

Creates an iterator from a value.Read more
1.53.0 ·Source§

impl<T, const N:usize>IntoIterator for[T; N]

Source§

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.

Source§

typeItem = T

The type of the elements being iterated over.
Source§

typeIntoIter =IntoIter<T, N>

Which kind of iterator are we turning this into?
1.0.0 ·Source§

impl<T, const N:usize>Ord for[T; N]
where T:Ord,

Implements comparison of arrayslexicographically.

Source§

fncmp(&self, other: &[T; N]) ->Ordering

This method returns anOrdering betweenself andother.Read more
1.21.0 ·Source§

fnmax(self, other: Self) -> Self
where Self:Sized,

Compares and returns the maximum of two values.Read more
1.21.0 ·Source§

fnmin(self, other: Self) -> Self
where Self:Sized,

Compares and returns the minimum of two values.Read more
1.50.0 ·Source§

fnclamp(self, min: Self, max: Self) -> Self
where Self:Sized,

Restrict a value to a certain interval.Read more
1.0.0 (const:unstable) ·Source§

impl<T, U, const N:usize>PartialEq<&[U]> for[T; N]
where T:PartialEq<U>,

Source§

fneq(&self, other: &&[U]) ->bool

Tests forself andother values to be equal, and is used by==.
Source§

fnne(&self, other: &&[U]) ->bool

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

impl<T, U, A, const N:usize>PartialEq<&[U; N]> forVec<T, A>
where A:Allocator, T:PartialEq<U>,

Source§

fneq(&self, other: &&[U; N]) ->bool

Tests forself andother values to be equal, and is used by==.
Source§

fnne(&self, other: &&[U; N]) ->bool

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

impl<T, U, A, const N:usize>PartialEq<&[U; N]> forVecDeque<T, A>
where A:Allocator, T:PartialEq<U>,

Source§

fneq(&self, other: &&[U; N]) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

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

impl<const N:usize>PartialEq<&[u8;N]> forByteStr

Source§

fneq(&self, other: &&[u8;N]) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

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

impl<const N:usize>PartialEq<&[u8;N]> forByteString

Source§

fneq(&self, other: &&[u8;N]) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.0.0 (const:unstable) ·Source§

impl<T, U, const N:usize>PartialEq<&mut[U]> for[T; N]
where T:PartialEq<U>,

Source§

fneq(&self, other: &&mut[U]) ->bool

Tests forself andother values to be equal, and is used by==.
Source§

fnne(&self, other: &&mut[U]) ->bool

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

impl<T, U, A, const N:usize>PartialEq<&mut[U; N]> forVecDeque<T, A>
where A:Allocator, T:PartialEq<U>,

Source§

fneq(&self, other: &&mut[U; N]) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.0.0 (const:unstable) ·Source§

impl<T, U, const N:usize>PartialEq<[U]> for[T; N]
where T:PartialEq<U>,

Source§

fneq(&self, other: &[U]) ->bool

Tests forself andother values to be equal, and is used by==.
Source§

fnne(&self, other: &[U]) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.0.0 (const:unstable) ·Source§

impl<T, U, const N:usize>PartialEq<[U; N]> for &[T]
where T:PartialEq<U>,

Source§

fneq(&self, other: &[U; N]) ->bool

Tests forself andother values to be equal, and is used by==.
Source§

fnne(&self, other: &[U; N]) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.0.0 (const:unstable) ·Source§

impl<T, U, const N:usize>PartialEq<[U; N]> for &mut[T]
where T:PartialEq<U>,

Source§

fneq(&self, other: &[U; N]) ->bool

Tests forself andother values to be equal, and is used by==.
Source§

fnne(&self, other: &[U; N]) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.0.0 (const:unstable) ·Source§

impl<T, U, const N:usize>PartialEq<[U; N]> for[T]
where T:PartialEq<U>,

Source§

fneq(&self, other: &[U; N]) ->bool

Tests forself andother values to be equal, and is used by==.
Source§

fnne(&self, other: &[U; N]) ->bool

Tests for!=. The default implementation is almost always sufficient,and should not be overridden without very good reason.
1.0.0 (const:unstable) ·Source§

impl<T, U, const N:usize>PartialEq<[U; N]> for[T; N]
where T:PartialEq<U>,

Source§

fneq(&self, other: &[U; N]) ->bool

Tests forself andother values to be equal, and is used by==.
Source§

fnne(&self, other: &[U; N]) ->bool

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

impl<T, U, A, const N:usize>PartialEq<[U; N]> forVec<T, A>
where A:Allocator, T:PartialEq<U>,

Source§

fneq(&self, other: &[U; N]) ->bool

Tests forself andother values to be equal, and is used by==.
Source§

fnne(&self, other: &[U; N]) ->bool

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

impl<T, U, A, const N:usize>PartialEq<[U; N]> forVecDeque<T, A>
where A:Allocator, T:PartialEq<U>,

Source§

fneq(&self, other: &[U; N]) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

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

impl<const N:usize>PartialEq<[u8;N]> forByteStr

Source§

fneq(&self, other: &[u8;N]) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

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

impl<const N:usize>PartialEq<[u8;N]> forByteString

Source§

fneq(&self, other: &[u8;N]) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

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

impl<const N:usize>PartialEq<ByteStr> for &[u8;N]

Source§

fneq(&self, other: &ByteStr) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

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

impl<const N:usize>PartialEq<ByteStr> for [u8;N]

Source§

fneq(&self, other: &ByteStr) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

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

impl<const N:usize>PartialEq<ByteString> for &[u8;N]

Source§

fneq(&self, other: &ByteString) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

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

impl<const N:usize>PartialEq<ByteString> for [u8;N]

Source§

fneq(&self, other: &ByteString) ->bool

Tests forself andother values to be equal, and is used by==.
1.0.0 ·Source§

fnne(&self, other:&Rhs) ->bool

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

impl<T, const N:usize>PartialOrd for[T; N]
where T:PartialOrd,

Implements comparison of arrayslexicographically.

Source§

fnpartial_cmp(&self, other: &[T; N]) ->Option<Ordering>

This method returns an ordering betweenself andother values if one exists.Read more
Source§

fnlt(&self, other: &[T; N]) ->bool

Tests less than (forself andother) and is used by the< operator.Read more
Source§

fnle(&self, other: &[T; N]) ->bool

Tests less than or equal to (forself andother) and is used by the<= operator.Read more
Source§

fnge(&self, other: &[T; N]) ->bool

Tests greater than or equal to (forself andother) and is used bythe>= operator.Read more
Source§

fngt(&self, other: &[T; N]) ->bool

Tests greater than (forself andother) and is used by the>operator.Read more
Source§

impl<'b, const N:usize>Pattern for &'b [char;N]

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

§Examples

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

typeSearcher<'a> =CharArrayRefSearcher<'a, 'b, N>

🔬This is a nightly-only experimental API. (pattern #27721)
Associated searcher for this pattern
Source§

fninto_searcher<'a>(self, haystack: &'astr) ->CharArrayRefSearcher<'a, 'b, N>

🔬This is a nightly-only experimental API. (pattern #27721)
Constructs the associated searcher fromself and thehaystack to search in.
Source§

fnis_contained_in<'a>(self, haystack: &'astr) ->bool

🔬This is a nightly-only experimental API. (pattern #27721)
Checks whether the pattern matches anywhere in the haystack
Source§

fnis_prefix_of<'a>(self, haystack: &'astr) ->bool

🔬This is a nightly-only experimental API. (pattern #27721)
Checks whether the pattern matches at the front of the haystack
Source§

fnstrip_prefix_of<'a>(self, haystack: &'astr) ->Option<&'astr>

🔬This is a nightly-only experimental API. (pattern #27721)
Removes the pattern from the front of haystack, if it matches.
Source§

fnis_suffix_of<'a>(self, haystack: &'astr) ->bool

🔬This is a nightly-only experimental API. (pattern #27721)
Checks whether the pattern matches at the back of the haystack
Source§

fnstrip_suffix_of<'a>(self, haystack: &'astr) ->Option<&'astr>

🔬This is a nightly-only experimental API. (pattern #27721)
Removes the pattern from the back of haystack, if it matches.
Source§

fnas_utf8_pattern(&self) ->Option<Utf8Pattern<'_>>

🔬This is a nightly-only experimental API. (pattern #27721)
Returns the pattern as utf-8 bytes if possible.
Source§

impl<const N:usize>Pattern for [char;N]

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

§Examples

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

typeSearcher<'a> =CharArraySearcher<'a, N>

🔬This is a nightly-only experimental API. (pattern #27721)
Associated searcher for this pattern
Source§

fninto_searcher<'a>(self, haystack: &'astr) ->CharArraySearcher<'a, N>

🔬This is a nightly-only experimental API. (pattern #27721)
Constructs the associated searcher fromself and thehaystack to search in.
Source§

fnis_contained_in<'a>(self, haystack: &'astr) ->bool

🔬This is a nightly-only experimental API. (pattern #27721)
Checks whether the pattern matches anywhere in the haystack
Source§

fnis_prefix_of<'a>(self, haystack: &'astr) ->bool

🔬This is a nightly-only experimental API. (pattern #27721)
Checks whether the pattern matches at the front of the haystack
Source§

fnstrip_prefix_of<'a>(self, haystack: &'astr) ->Option<&'astr>

🔬This is a nightly-only experimental API. (pattern #27721)
Removes the pattern from the front of haystack, if it matches.
Source§

fnis_suffix_of<'a>(self, haystack: &'astr) ->bool

🔬This is a nightly-only experimental API. (pattern #27721)
Checks whether the pattern matches at the back of the haystack
Source§

fnstrip_suffix_of<'a>(self, haystack: &'astr) ->Option<&'astr>

🔬This is a nightly-only experimental API. (pattern #27721)
Removes the pattern from the back of haystack, if it matches.
Source§

fnas_utf8_pattern(&self) ->Option<Utf8Pattern<'_>>

🔬This is a nightly-only experimental API. (pattern #27721)
Returns the pattern as utf-8 bytes if possible.
1.51.0 ·Source§

impl<T, const N:usize>SlicePattern for[T; N]

Source§

typeItem = T

🔬This is a nightly-only experimental API. (slice_pattern #56345)
The element type of the slice being matched on.
Source§

fnas_slice(&self) -> &[<[T; N] asSlicePattern>::Item]

🔬This is a nightly-only experimental API. (slice_pattern #56345)
Currently, the consumers ofSlicePattern need a slice.
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.

letbytes: [u8;3] = [1,0,2];letbytes_head:&[u8;2] = <&[u8;2]>::try_from(&bytes[0..2]).unwrap();assert_eq!(1, u16::from_le_bytes(*bytes_head));letbytes_tail:&[u8;2] = bytes[1..3].try_into().unwrap();assert_eq!(512, u16::from_le_bytes(*bytes_tail));
Source§

typeError =TryFromSliceError

The type returned in the event of a conversion error.
Source§

fntry_from(slice: &'a[T]) ->Result<&'a[T; N],TryFromSliceError>

Performs the conversion.
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.

letbytes: [u8;3] = [1,0,2];letbytes_head: [u8;2] = <[u8;2]>::try_from(&bytes[0..2]).unwrap();assert_eq!(1, u16::from_le_bytes(bytes_head));letbytes_tail: [u8;2] = bytes[1..3].try_into().unwrap();assert_eq!(512, u16::from_le_bytes(bytes_tail));
Source§

typeError =TryFromSliceError

The type returned in the event of a conversion error.
Source§

fntry_from(slice: &[T]) ->Result<[T; N],TryFromSliceError>

Performs the conversion.
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.

letmutbytes: [u8;3] = [1,0,2];letbytes_head:&mut[u8;2] = <&mut[u8;2]>::try_from(&mutbytes[0..2]).unwrap();assert_eq!(1, u16::from_le_bytes(*bytes_head));letbytes_tail:&mut[u8;2] = (&mutbytes[1..3]).try_into().unwrap();assert_eq!(512, u16::from_le_bytes(*bytes_tail));
Source§

typeError =TryFromSliceError

The type returned in the event of a conversion error.
Source§

fntry_from(slice: &'a mut[T]) ->Result<&'a mut[T; N],TryFromSliceError>

Performs the conversion.
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.

letmutbytes: [u8;3] = [1,0,2];letbytes_head: [u8;2] = <[u8;2]>::try_from(&mutbytes[0..2]).unwrap();assert_eq!(1, u16::from_le_bytes(bytes_head));letbytes_tail: [u8;2] = (&mutbytes[1..3]).try_into().unwrap();assert_eq!(512, u16::from_le_bytes(bytes_tail));
Source§

typeError =TryFromSliceError

The type returned in the event of a conversion error.
Source§

fntry_from(slice: &mut[T]) ->Result<[T; N],TryFromSliceError>

Performs the conversion.
1.43.0 ·Source§

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>

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.

Source§

typeError =Box<[T]>

The type returned in the event of a conversion error.
1.66.0 ·Source§

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>

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:

letstate: Box<[f32;100]> =vec![1.0;100].try_into().unwrap();assert_eq!(state.len(),100);
Source§

typeError =Vec<T>

The type returned in the event of a conversion error.
1.48.0 ·Source§

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>>

Gets the entire contents of theVec<T> as an array,if its size exactly matches that of the requested array.

§Examples
assert_eq!(vec![1,2,3].try_into(),Ok([1,2,3]));assert_eq!(<Vec<i32>>::new().try_into(),Ok([]));

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.

letmutv = String::from("hello world").into_bytes();v.sort();v.truncate(2);let[a, b]: [_;2] = v.try_into().unwrap();assert_eq!(a,b' ');assert_eq!(b,b'd');
Source§

typeError =Vec<T, A>

The type returned in the event of a conversion error.
Source§

impl<T, const N:usize>CloneFromCell for[T; N]
where T:CloneFromCell,

Source§

impl<T, const N:usize>ConstParamTy_ for[T; N]
where T:ConstParamTy_,

1.58.0 ·Source§

impl<T, const N:usize>Copy for[T; N]
where T:Copy,

1.0.0 (const:unstable) ·Source§

impl<T, const N:usize>Eq for[T; N]
where T:Eq,

Source§

impl<T, const N:usize>StructuralPartialEq for[T; N]

Auto Trait Implementations§

§

impl<T, const N:usize>Freeze for [MaybeUninit<T>;N]
where T:Freeze,

§

impl<T, const N:usize>RefUnwindSafe for [MaybeUninit<T>;N]
where T:RefUnwindSafe,

§

impl<T, const N:usize>Send for [MaybeUninit<T>;N]
where T:Send,

§

impl<T, const N:usize>Sync for [MaybeUninit<T>;N]
where T:Sync,

§

impl<T, const N:usize>Unpin for [MaybeUninit<T>;N]
where T:Unpin,

§

impl<T, const N:usize>UnwindSafe for [MaybeUninit<T>;N]
where T:UnwindSafe,

Blanket Implementations§

Source§

impl<T>Any for T
where T: 'static + ?Sized,

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

impl<T>Borrow<T> for T
where T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

impl<T>BorrowMut<T> for T
where T: ?Sized,

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>CloneToUninit for T
where T:Clone,

Source§

unsafe fnclone_to_uninit(&self, dest:*mutu8)

🔬This is a nightly-only experimental API. (clone_to_uninit #126799)
Performs copy-assignment fromself todest.Read more
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U>Into<U> for T
where U:From<T>,

Source§

fninto(self) -> U

CallsU::from(self).

That is, this conversion is whatever the implementation ofFrom<T> for U chooses to do.

Source§

impl<T>ToOwned for T
where T:Clone,

Source§

typeOwned = T

The resulting type after obtaining ownership.
Source§

fnto_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning.Read more
Source§

fnclone_into(&self, target:&mut T)

Uses borrowed data to replace owned data, usually by cloning.Read more
Source§

impl<T, U>TryFrom<U> for T
where U:Into<T>,

Source§

typeError =Infallible

The type returned in the event of a conversion error.
Source§

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U>TryInto<U> for T
where U:TryFrom<T>,

Source§

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.

[8]ページ先頭

©2009-2026 Movatter.jp