1 个不稳定版本
0.1.0 | 2024 年 8 月 10 日 |
---|
#460 在 过程宏 中
每月 106 次下载
13KB
185 行
type-utilities-rs
Rust 中的类型工具。
省略
创建一个新的 Struct,省略指定的字段
use type_utilities_rs::omit;
// Create a new struct `NewS` with omitted field `b`
#[omit(NewS, [b])]
struct S {
a: i32,
b: &str,
}
// `NewS` will only have field `a`
let _ = NewS { a: 1 };
当未指定字段时,它将与原始结构相同
use type_utilities_rs::omit;
#[omit(NewS)]
struct S<'a> {
a: i32,
b: &'a str,
}
// `NewS` is same as the original struct `S`
let _ = NewS { a: 1, b: "hello" };
选择
创建一个新的 Struct,选择指定的字段
use type_utilities_rs::pick;
// Create a new struct `NewS` with picked field `b`
#[pick(NewS, [b])]
struct S<'a> {
a: i32,
b: &'a str,
c: f64,
}
// `NewS` will only have field `b`
let _ = NewS { b: "hello" };
当未指定字段时,它将是空的 Struct
use type_utilities_rs::pick;
#[pick(NewS)]
struct S {
a: i32,
b: f64,
}
// `NewS` will be empty struct
let _ = NewS {};
部分
将所有字段更改为 Option
类型
use type_utilities_rs::partial;
// Create a new struct `NewS` with all fields optional
#[partial(NewS)]
struct S<'a> {
a: i32,
b: &'a str,
c: f64,
}
// `NewS` will have all fields optional
let _ = NewS { a: Some(1), b: Some("hello"), c: Some(1.5) };
当字段已经是 Option
时,没有效果
use type_utilities_rs::partial;
#[partial(NewS)]
struct S {
a: i32,
b: Option<f64>,
}
let _ = NewS { a: Some(1), b: Some(1.1) };
必需
从 Option
类型中解包所有字段
use type_utilities_rs::required;
// Create a new struct `NewS` with all fields optional
#[required(NewS)]
struct S<'a> {
a: Option<i32>,
b: Option<&'a str>,
c: f64,
}
// `NewS` will have all fields.
// When the field is not [`Option`], it's no effect
let _ = NewS { a: 1, b: "hello", c: 1.5 };
依赖项
~260–710KB
~17K SLoC