1个不稳定版本

0.1.0 2022年2月18日

#1848 in 数据结构

MIT/Apache

7KB
90

fieldfilter

fieldfilter 是一个非常简单的crate,使用起来很简单。基本上它提供的是一种将结构体“过滤”为自身更小集合的方法。

以下是一个示例

use std::collections::HashSet;
use fieldfilter::FieldFilterable;

struct User {
    id: u32,
    name: String,
    email: String,
}
#[derive(Debug, FieldFilterable)]
#[field_filterable_on(User)]
struct FilteredUser {
    id: u32,
    name: Option<String>,
    email: Option<String>,
}

let user = User {
    id: 1,
    name: "Allen".to_string(),
    email: "[email protected]".to_string(),
};

let fields = HashSet::from(["name".to_owned()]);

let filtered_user: FilteredUser = FieldFilterable::field_filter(user, fields);
println!("{:?}", filtered_user);

这种行为在您想要从某些结构体或实体中删除某些字段的可见性时非常有用,无论是将某些SQL行作为REST或GraphQL响应返回,或者只是一个简单的净化过程。

灵感

这个crate存在的原因是因为我有一个特定的用例。我想能够将ORM中的模型映射到仅包含我想要可见的字段的序列化HTTP响应中,这些字段由我选择的授权引擎中的策略文件指定。

不用说,这也是我最终接触宏的原因!

依赖

~1.5MB
~35K SLoC