File: README.md

package info (click to toggle)
rust-array-init 0.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 120 kB
  • sloc: makefile: 4
file content (47 lines) | stat: -rw-r--r-- 1,304 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# array-init

[Documentation](https://docs.rs/array-init)

[Crates.io](https://crates.io/crates/array-init)


(still kinda experimental, API may change, may be secretly unsafe)

The `array-init` crate allows you to initialize arrays
with an initializer closure that will be called
once for each element until the array is filled.

This way you do not need to default-fill an array
before running initializers. Rust currently only
lets you either specify all initializers at once,
individually (`[a(), b(), c(), ...]`), or specify
one initializer for a `Copy` type (`[a(); N]`),
which will be called once with the result copied over.

# Examples:

```rust
// Initialize an array of length 50 containing
// successive squares

let arr: [usize; 50] = array_init::array_init(|i| i * i);

// Initialize an array from an iterator
// producing an array of [1,2,3,4] repeated

let four = [1,2,3,4];
let mut iter = four.iter().copied().cycle();
let arr: [u32; 50] = array_init::from_iter(iter).unwrap();

// Closures can also mutate state. We guarantee that they will be called
// in order from lower to higher indices.

let mut last = 1u64;
let mut secondlast = 0;
let fibonacci: [u64; 50] = array_init::array_init(|_| {
    let this = last + secondlast;
    secondlast = last;
    last = this;
    this
});
```