Primitive Type array1.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:

  • A list with each element, i.e., [x, y, z].
  • A repeat expression [x; N], which produces an array with N copies of x. The type of x must be Copy.

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

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);
}
Run

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

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

for x in &array { }
Run

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);
Run

Editions

Prior to Rust 1.53, arrays did not implement IntoIterator by value, so the method call array.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, ignoring IntoIterator by value. In the future, the behavior on the 2015 and 2018 edition might be made consistent to the behavior of later editions.

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` or `std::array::IntoIter::new`:
for item in IntoIterator::into_iter(array).enumerate() {
    let (i, x): (usize, i32) = item;
    println!("array[{}] = {}", i, x);
}
Run

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

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);
}
Run

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:

  • use iter, equivalent to the old behavior, creating references
  • use array::IntoIter, equivalent to the post-2021 behavior (Rust 1.51+)
  • replace for ... in array.into_iter() { with for ... in array {, equivalent to the post-2021 behavior (Rust 1.53+)
use std::array::IntoIter;

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 IntoIter::new(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 IntoIter::new(array).enumerate() {
    let (i, x): (usize, i32) = item;
    println!("array[{}] = {}", i, x);
}
Run

Implementations

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

pub fn map<F, U>(self, f: F) -> [U; N] where
    F: FnMut(T) -> U, 
[src]

🔬 This is a nightly-only experimental API. (array_map #75243)

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

Examples

#![feature(array_map)]
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]);
Run

pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N][src]

🔬 This is a nightly-only experimental API. (array_zip #80094)

‘Zips up’ two arrays into a single array of pairs.

zip() returns a new array where every element is a tuple where the first element comes from the first array, and the second element comes from the second array. In other words, it zips two arrays together, into a single one.

Examples

#![feature(array_zip)]
let x = [1, 2, 3];
let y = [4, 5, 6];
let z = x.zip(y);
assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
Run

pub fn as_slice(&self) -> &[T]

Notable traits for &[u8]

impl Read for &[u8]impl Write for &mut [u8]
[src]

🔬 This is a nightly-only experimental API. (array_methods #76118)

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

pub fn as_mut_slice(&mut self) -> &mut [T]

Notable traits for &[u8]

impl Read for &[u8]impl Write for &mut [u8]
[src]

🔬 This is a nightly-only experimental API. (array_methods #76118)

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

pub fn each_ref(&self) -> [&T; N][src]

🔬 This is a nightly-only experimental API. (array_methods #76118)

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

Example

#![feature(array_methods)]

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]);
Run

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

#![feature(array_methods, array_map)]

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);
Run

pub fn each_mut(&mut self) -> [&mut T; N][src]

🔬 This is a nightly-only experimental API. (array_methods #76118)

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

Example

#![feature(array_methods)]

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]);
Run

Trait Implementations

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

pub fn as_mut(&mut self) -> &mut [T]

Notable traits for &[u8]

impl Read for &[u8]impl Write for &mut [u8]
[src]

Performs the conversion.

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

pub fn as_ref(&self) -> &[T]

Notable traits for &[u8]

impl Read for &[u8]impl Write for &mut [u8]
[src]

Performs the conversion.

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

pub fn borrow(&self) -> &[T]

Notable traits for &[u8]

impl Read for &[u8]impl Write for &mut [u8]
[src]

Immutably borrows from an owned value. Read more

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

pub fn borrow_mut(&mut self) -> &mut [T]

Notable traits for &[u8]

impl Read for &[u8]impl Write for &mut [u8]
[src]

Mutably borrows from an owned value. Read more

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

pub fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>[src]

Formats the value using the given formatter. Read more

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

pub fn default() -> [T; 23][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 26][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 31][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 25][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 9][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 30][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 17][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 19][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 6][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 20][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 15][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 28][src]

Returns the “default value” for a type. Read more

impl<T> Default for [T; 0]1.4.0[src]

pub fn default() -> [T; 0][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 1][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 10][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 8][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 29][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 4][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 14][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 21][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 2][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 11][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 3][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 5][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 7][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 22][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 32][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 16][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 27][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 13][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 18][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 12][src]

Returns the “default value” for a type. Read more

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

pub fn default() -> [T; 24][src]

Returns the “default value” for a type. Read more

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

pub fn hash<H>(&self, state: &mut H) where
    H: Hasher
[src]

Feeds this value into the given Hasher. Read more

fn hash_slice<H>(data: &[Self], state: &mut H) where
    H: Hasher
1.3.0[src]

Feeds a slice of this type into the given Hasher. Read more

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

type Output = <[T] as Index<I>>::Output

The returned type after indexing.

pub fn index(&self, index: I) -> &<[T; N] as Index<I>>::Output[src]

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

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

pub fn index_mut(&mut self, index: I) -> &mut <[T; N] as Index<I>>::Output[src]

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

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

pub fn into_iter(self) -> <[T; N] as IntoIterator>::IntoIter[src]

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 implements Copy, 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.

type Item = T

The type of the elements being iterated over.

type IntoIter = IntoIter<T, N>

Which kind of iterator are we turning this into?

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

type Item = &'a mut T

The type of the elements being iterated over.

type IntoIter = IterMut<'a, T>

Which kind of iterator are we turning this into?

pub fn into_iter(self) -> IterMut<'a, T>

Notable traits for IterMut<'a, T>

impl<'a, T> Iterator for IterMut<'a, T> type Item = &'a mut T;
[src]

Creates an iterator from a value. Read more

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

type Item = &'a T

The type of the elements being iterated over.

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?

pub fn into_iter(self) -> Iter<'a, T>

Notable traits for Iter<'a, T>

impl<'a, T> Iterator for Iter<'a, T> type Item = &'a T;
[src]

Creates an iterator from a value. Read more

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

Implements comparison of arrays lexicographically.

pub fn cmp(&self, other: &[T; N]) -> Ordering[src]

This method returns an Ordering between self and other. Read more

#[must_use]
fn max(self, other: Self) -> Self
1.21.0[src]

Compares and returns the maximum of two values. Read more

#[must_use]
fn min(self, other: Self) -> Self
1.21.0[src]

Compares and returns the minimum of two values. Read more

#[must_use]
fn clamp(self, min: Self, max: Self) -> Self
1.50.0[src]

Restrict a value to a certain interval. Read more

impl<'_, A, B, const N: usize> PartialEq<&'_ [B]> for [A; N] where
    A: PartialEq<B>, 
[src]

pub fn eq(&self, other: &&[B]) -> bool[src]

This method tests for self and other values to be equal, and is used by ==. Read more

pub fn ne(&self, other: &&[B]) -> bool[src]

This method tests for !=.

impl<'_, A, B, const N: usize> PartialEq<&'_ mut [B]> for [A; N] where
    A: PartialEq<B>, 
[src]

pub fn eq(&self, other: &&mut [B]) -> bool[src]

This method tests for self and other values to be equal, and is used by ==. Read more

pub fn ne(&self, other: &&mut [B]) -> bool[src]

This method tests for !=.

impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N] where
    A: PartialEq<B>, 
[src]

pub fn eq(&self, other: &[B; N]) -> bool[src]

This method tests for self and other values to be equal, and is used by ==. Read more

pub fn ne(&self, other: &[B; N]) -> bool[src]

This method tests for !=.

impl<A, B, const N: usize> PartialEq<[B]> for [A; N] where
    A: PartialEq<B>, 
[src]

pub fn eq(&self, other: &[B]) -> bool[src]

This method tests for self and other values to be equal, and is used by ==. Read more

pub fn ne(&self, other: &[B]) -> bool[src]

This method tests for !=.

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

pub fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering>[src]

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

pub fn lt(&self, other: &[T; N]) -> bool[src]

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

pub fn le(&self, other: &[T; N]) -> bool[src]

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

pub fn ge(&self, other: &[T; N]) -> bool[src]

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

pub fn gt(&self, other: &[T; N]) -> bool[src]

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

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

type Item = T

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

stopgap trait for slice patterns

The element type of the slice being matched on.

pub fn as_slice(&self) -> &[<[T; N] as SlicePattern>::Item]

Notable traits for &[u8]

impl Read for &[u8]impl Write for &mut [u8]
[src]

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

stopgap trait for slice patterns

Currently, the consumers of SlicePattern need a slice.

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

type Error = TryFromSliceError

The type returned in the event of a conversion error.

pub fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError>[src]

Performs the conversion.

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

type Error = TryFromSliceError

The type returned in the event of a conversion error.

pub fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError>[src]

Performs the conversion.

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

type Error = TryFromSliceError

The type returned in the event of a conversion error.

pub fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError>[src]

Performs the conversion.

impl<T, A, const N: usize> TryFrom<Vec<T, A>> for [T; N] where
    A: Allocator
1.48.0[src]

pub fn try_from(vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>>[src]

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

Examples

use std::convert::TryInto;
assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
Run

If the length doesn’t match, the input comes back in Err:

use std::convert::TryInto;
let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
Run

If you’re fine with just getting a prefix of the Vec<T>, you can call .truncate(N) first.

use std::convert::TryInto;
let mut v = 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');
Run

type Error = Vec<T, A>

The type returned in the event of a conversion error.

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

Auto Trait Implementations

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

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

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

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

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

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

impl<T> From<T> for T[src]

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

pub fn to_owned(&self) -> T[src]

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

pub fn clone_into(&self, target: &mut T)[src]

🔬 This is a nightly-only experimental API. (toowned_clone_into #41263)

recently added

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

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>[src]

Performs the conversion.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>[src]

Performs the conversion.