#structs #proc-macro #derivative #generate #safe #refactoring #enums

mapstruct

使用 proc-macro 创建结构体的安全重构派生

4 个版本 (破坏性更新)

0.4.0 2024 年 2 月 9 日
0.3.0 2024 年 2 月 8 日
0.2.0 2024 年 1 月 23 日
0.1.0 2024 年 1 月 23 日

#1644 in Rust 模式

每月 38 次下载

MIT 许可证

4KB

Mapstruct-Rs

A proc macro that generates new structs with the variations of the fields you want. You use it by annotating a struct with #[derive(Mapstruct)] and then you can use the mapstruct(...) macro to generate new structs. The syntax is similar to the struct definition syntax, but you only specify the fields and generics you want to change. You use the + operator to add a field or generic, the - operator to remove a field or generic and the ~ operator to change the type or name of a field or generic.

示例结构体

use mapstruct_rs::Mapstruct;

#[derive(MapStruct)]
#[mapstruct(
    #[derive(Debug)]
    struct Y<
        +'a,
    > {
        ~id -> pub id,
        ~name: &'a str,
        ~some: &'a str,
        +last_name: &'a str,
        -height,
    }
)]
struct X {
    id: i64,
    name: String,
    age: i32,
    height: f32,
    some: String,
}

上述代码将生成以下结构体

#[derive(Debug)]
struct Y<'a> {
    pub id: i64,
    name: &'a str,
    age: i32,
    some: &'a str,
    last_name: &'a str,
}

示例枚举

use mapstruct_rs::Mapstruct;

#[derive(MapStruct)]
#[mapstruct(
    #[derive(Debug)]
    enum Y {
        A {
            id: i64,
        },
        ~B(~i32, _),
        +D(i8),
    }
)]
enum X {
    A(i64),
    B(i32, i8),
    C(i16),
}

上述代码将生成以下枚举

#[derive(Debug)]
enum Y {
    A {
        id: i64,
    },
    B(i32),
    C(i16),
    D(i8)
}

依赖项

~300–740KB
~18K SLoC