7 releases (4 stable)

Uses old Rust 2015

1.1.0 Aug 26, 2017
1.0.2 Jun 3, 2017
1.0.1 Jan 20, 2017
1.0.0 Dec 27, 2016
0.1.2 Dec 19, 2016

#2277 in Rust patterns

Download history 1591/week @ 2024-10-11 1754/week @ 2024-10-18 1656/week @ 2024-10-25 1848/week @ 2024-11-01 1371/week @ 2024-11-08 1530/week @ 2024-11-15 1664/week @ 2024-11-22 2091/week @ 2024-11-29 2568/week @ 2024-12-06 2521/week @ 2024-12-13 1665/week @ 2024-12-20 1456/week @ 2024-12-27 1994/week @ 2025-01-03 1713/week @ 2025-01-10 1992/week @ 2025-01-17 1703/week @ 2025-01-24

7,723 downloads per month
Used in 28 crates (3 directly)

Unlicense

8KB
85 lines

init_with

Documentation

Have you wanted to be able to initialize a fixed array in Rust by calling a function to create each element? Now you can!

use init_with::InitWith;

let my_array = {
    let mut seed = Vec::new();
    let mut next_val = 0;

    <[Vec<u32>; 3]>::init_with(|| {
        seed.push(next_val);
        next_val += 1;
        seed.clone()
    })
};

assert_eq!(my_array, [vec![0], vec![0, 1], vec![0, 1, 2]]);

Alternatively, init_with_indices can be used to more easily create array entries based on their index:

use init_with::InitWith;

let squares = <[usize; 5]>::init_with_indices(|i| i*i);

assert_eq!(squares, [0,1,4,9,16]);

This crate lets you initialize the array elements in a functional manner while hiding the unsafe code that's needed to do so.

To import this crate, put the following into your Cargo.toml:

[dependencies]
init_with = "1.1.0"

...and the following in your crate root:

extern crate init_with;

No runtime deps