pub trait InitWith<T> {
// Required methods
fn init_with<F>(init: F) -> Self
where F: FnMut() -> T,
Self: Sized;
fn init_with_indices<F>(init: F) -> Self
where F: FnMut(usize) -> T,
Self: Sized;
}
Expand description
A trait that allows you to create an instance of a type by using a given function to generate each element.
Required Methods§
Sourcefn init_with<F>(init: F) -> Self
fn init_with<F>(init: F) -> Self
Create a new instance of this type using the given function to fill elements.
§Examples
Prefilling an array with a Vec, with no unsafe code:
use init_with::InitWith;
let src = vec![1, 2, 3];
let dest: [i32; 3] = {
let mut idx = 0;
<[i32; 3]>::init_with(|| {
let val = src[idx];
idx += 1;
val
})
};
assert_eq!(src, dest);
Sourcefn init_with_indices<F>(init: F) -> Self
fn init_with_indices<F>(init: F) -> Self
Create a new instance of this type to fill elements by mapping the given function over the new array’s indices.
§Examples
Prefilling an array of even numbers, with no unsafe code:
use init_with::InitWith;
let src = vec![0, 2, 4];
let dest = <[i32; 3]>::init_with_indices(|x| 2*x as i32);
assert_eq!(src, dest);