2个版本
0.1.1 | 2024年5月20日 |
---|---|
0.1.0 | 2024年5月17日 |
#265 in 进程宏
每月608次下载
29KB
490 行
substruct
Substruct是一个进程宏,允许您轻松声明作为另一个结构体子集的结构体。
简单示例
substruct的基本使用如下
use substruct::substruct;
#[substruct(LimitedQueryParams)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct QueryParams {
#[substruct(LimitedQueryParams)]
pub name: Option<String>,
#[substruct(LimitedQueryParams)]
pub parent: Option<String>,
pub limit: usize
}
展开后产生以下内容
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct QueryParams {
pub name: Option<String>,
pub parent: Option<String>,
pub limit: usize
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LimitedQueryParams {
pub name: Option<String>,
pub parent: Option<String>,
}
复杂示例
Substruct还支持复制属性或为子结构体的子集添加特定属性。
use std::time::SystemTime;
use substruct::substruct;
#[substruct(PostQueryParams, ThreadQueryParams)]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct QueryParams {
/// Query only within forums with this id
pub forum: Option<u64>,
/// Query only with threads with this id.
#[substruct(PostQueryParams)]
pub thread: Option<u64>,
/// The username to search.
#[substruct(PostQueryParams, ThreadQueryParams)]
// Alias only applied for ThreadQueryParams
#[substruct_attr(ThreadQueryParams, serde(alias = "username"))]
pub user: Option<String>,
#[substruct(PostQueryParams, ThreadQueryParams)]
// Field is renamed (in serde) for PostQueryParams and ThreadQueryParams
// but not for QueryParams.
#[substruct_attr(not(QueryParams), serde(rename = "before_ts"))]
pub before: Option<SystemTime>,
#[substruct(PostQueryParams, ThreadQueryParams)]
#[substruct_attr(not(QueryParams), serde(rename = "before_ts"))]
pub after: Option<SystemTime>,
// Limit is only present on QueryParams.
pub limit: Option<usize>,
}
限制
Substruct支持泛型,但如果泛型参数没有被所有子结构体使用,则可能会失败。
另请参阅
依赖关系
~1–1.6MB
~32K SLoC