Crate default_option_arr

source ·
Expand description

When dealing with non-Copy/Clone types T, such as arrays of type [Option<T>; N] cannot be created even though the default type None could be applied.

For a given type

// This type does not implement Copy.
struct Complicated;

The following code fails to compile with the compiler error “the trait Copy is not implemented for Complicated”:

let arr: [Option<Complicated>; 10] = [None; 10];

This crate simplifies array creation of these cases through the none_arr! macro:

let arr = none_arr![Complicated; 10];

// The result is an array of Option<Complicated>.
let arr: [Option<Complicated>; 10] = arr;

assert_eq!(arr.len(), 10);
for item in arr.into_iter() {
    assert!(item.is_none());
}

Macros§

  • Creates an array of type [Option<T>; N] and default-initializes it to None for every element.
  • Creates an array of type [Cell<Option<T>>; N] and default-initializes it to Cell:new(None) for every element. Similar to none_arr, plus a Cell.
  • Creates an array of type [RefCell<Option<T>>; N] and default-initializes it to Cell:new(None) for every element. Similar to none_cell_arr, but with a RefCell.