https://github.com/sunsided/default-option-arr
Macros for simple default initialization of arrays of option types
https://github.com/sunsided/default-option-arr
rust rust-macros
Last synced: 4 months ago
JSON representation
Macros for simple default initialization of arrays of option types
- Host: GitHub
- URL: https://github.com/sunsided/default-option-arr
- Owner: sunsided
- License: eupl-1.2
- Created: 2023-05-27T18:54:46.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2025-06-24T09:03:55.000Z (about 1 year ago)
- Last Synced: 2025-11-28T08:31:17.469Z (8 months ago)
- Topics: rust, rust-macros
- Language: Rust
- Homepage: https://crates.io/crates/default-option-arr
- Size: 19.5 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Default Array-of-Option\ Macros
Macros to make your life easier when dealing with default-initialized
arrays of `Option` or `Cell>` for non-`Copy` types of `T` to `[None, ..]`.
### You may need it if ...
- You need an array of `[Option; N]` initialized to `[None; N]`, or
- You need an array of `[Cell>; N]` initialized to `[Cell::new(None); N]`, or
- You need an array of `[RefCell>; N]` initialized to `[RefCell::new(None); N]`.
### You will not need it if ...
- Your types already implement `Copy` or `Clone` and you don't need cells.
- You require `#![forbid(unsafe_code)]`.
## Examples
```rust
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; 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; 10] = arr;
assert_eq!(arr.len(), 10);
}
```
Likewise, arrays of `Cell>` can be created.
```rust
fn cell_works() {
let arr: [Cell>; 10] = none_cell_arr![Complicated; 10];
let arr: [RefCell>; 10] = none_refcell_arr![Complicated; 10];
}
```
## I cannot have unsafe code
If you cannot have `unsafe` code in your project, something like the following can be used:
```rust
fn not_fun() {
let arr: [Option; 10] = (0..10)
.into_iter()
.map(|_| None)
.collect::>()
.try_into()
.map_err(|_| "try_into failed") // Debug required otherwise
.expect("initialization failed");
}
```