#options #array #default-init

无std default-option-arr

用于简单初始化option类型数组的宏

3个不稳定版本

0.2.0 2024年7月6日
0.1.1 2023年7月8日
0.1.0 2023年5月27日

#78 in 无标准库

Download history 120/week @ 2024-07-02 17/week @ 2024-07-09 16/week @ 2024-07-23 16/week @ 2024-07-30

每月 57 次下载
用于 arraysetcell

EUPL-1.2

12KB
105 代码行

默认Array-of-Option<T>宏

宏,用于简化处理默认初始化的Option类型数组或Cell类型数组,适用于非Copy类型T,将其初始化为[code][None, ..., None]

你可能需要它,如果 ...

  • 你需要一个初始化为[code][None, ..., None]的[code][Option; N]数组,或者
  • 你需要一个初始化为[code][Cell::new(None); N]的[code][Cell; N]数组,或者
  • 你需要一个初始化为[code][RefCell::new(None); N]的[code][RefCell; N]数组。

如果你不需要它 ...

  • 如果你的类型已经实现了Copy或Clone,并且你不需要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);
}

同样,可以创建 Cell<Option<T>> 的数组。

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];
}

不能有不安全代码

如果您的项目中不能有不安全的代码,可以使用以下类似的内容

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");
}

无运行时依赖

功能