Crates.io | default-option-arr |
lib.rs | default-option-arr |
version | 0.2.0 |
source | src |
created_at | 2023-05-27 19:44:38.039676 |
updated_at | 2024-07-06 22:29:55.133377 |
description | Macros for simple default initialization of arrays of option types |
homepage | |
repository | https://github.com/sunsided/default-option-arr |
max_upload_size | |
id | 876082 |
size | 26,317 |
Macros to make your life easier when dealing with default-initialized
arrays of Option<T>
or Cell<Option<T>>
for non-Copy
types of T
to [None, ..]
.
[Option<T>; N]
initialized to [None; N]
, or[Cell<Option<T>>; N]
initialized to [Cell::new(None); N]
, or[RefCell<Option<T>>; N]
initialized to [RefCell::new(None); N]
.Copy
or Clone
and you don't need cells.#![forbid(unsafe_code)]
.use core::cell::Cell;
use arraysetcell::ArraySetCell;
// This type does not implement Copy.
struct Complicated;
fn it_works() {
// This doesn't compile:
let arr: [Option<Complicated>; 10] = [None; 10];
// This does:
let arr = none_arr![Complicated; 10];
// [None, None, None, ...]
assert_eq!(arr.len(), 10);
for item in arr.into_iter() {
assert!(item.is_none());
}
// The created type is an array.
let arr: [Option<Complicated>; 10] = arr;
assert_eq!(arr.len(), 10);
}
Likewise, arrays of Cell<Option<T>>
can be created.
fn cell_works() {
let arr: [Cell<Option<Complicated>>; 10] = none_cell_arr![Complicated; 10];
let arr: [RefCell<Option<Complicated>>; 10] = none_refcell_arr![Complicated; 10];
}
If you cannot have unsafe
code in your project, something like the following can be used:
fn not_fun() {
let arr: [Option<Complicated>; 10] = (0..10)
.into_iter()
.map(|_| None)
.collect::<Vec<_>>()
.try_into()
.map_err(|_| "try_into failed") // Debug required otherwise
.expect("initialization failed");
}