]> git.lizzy.rs Git - rust.git/commit - src/tools/rust-analyzer
Rollup merge of #75644 - c410-f3r:array, r=yaahc
authorGuillaume Gomez <guillaume1.gomez@gmail.com>
Sat, 9 Oct 2021 15:08:38 +0000 (17:08 +0200)
committerGitHub <noreply@github.com>
Sat, 9 Oct 2021 15:08:38 +0000 (17:08 +0200)
commit86bf3ce8591343bcc2442e95d6432f3b78e07cc5
tree597fe7e59099eae477085dd415540bfb5cbb4e63
parentbb918d0a5bf22211df0423f7474e4e4056978007
parent85c4a52807d6137505b0d1419cc800c210d79159
Rollup merge of #75644 - c410-f3r:array, r=yaahc

Add 'core::array::from_fn' and 'core::array::try_from_fn'

These auxiliary methods fill uninitialized arrays in a safe way and are particularly useful for elements that don't implement `Default`.

```rust
// Foo doesn't implement Default
struct Foo(usize);

let _array = core::array::from_fn::<_, _, 2>(|idx| Foo(idx));
```

Different from `FromIterator`, it is guaranteed that the array will be fully filled and no error regarding uninitialized state will be throw. In certain scenarios, however, the creation of an **element** can fail and that is why the `try_from_fn` function is also provided.

```rust
#[derive(Debug, PartialEq)]
enum SomeError {
    Foo,
}

let array = core::array::try_from_fn(|i| Ok::<_, SomeError>(i));
assert_eq!(array, Ok([0, 1, 2, 3, 4]));

let another_array = core::array::try_from_fn(|_| Err(SomeError::Foo));
assert_eq!(another_array, Err(SomeError::Foo));
 ```
library/core/src/array/mod.rs
library/core/tests/lib.rs