#struct #subsets #create #proc-macro #another #no-std #query-parameters

no-std substruct

一个用于创建结构体子集的进程宏

2个版本

0.1.1 2024年5月20日
0.1.0 2024年5月17日

#265 in 进程宏

Download history 315/week @ 2024-05-15 325/week @ 2024-05-22 316/week @ 2024-05-29 118/week @ 2024-06-05 178/week @ 2024-06-12 176/week @ 2024-06-19 248/week @ 2024-06-26 157/week @ 2024-07-03 92/week @ 2024-07-10 213/week @ 2024-07-17 82/week @ 2024-07-24 214/week @ 2024-07-31

每月608次下载

MIT/Apache

29KB
490

substruct

crates.io license docs.rs ci

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