Rust宏代码生成库schematic_macros的使用:自动化Schema构建与过程宏开发
Rust宏代码生成库schematic_macros的使用:自动化Schema构建与过程宏开发
安装
在项目目录中运行以下Cargo命令:
cargo add schematic_macros
或者在Cargo.toml中添加以下行:
schematic_macros = "0.18.11"
示例
以下是一个使用schematic_macros进行自动化Schema构建与过程宏开发的完整示例:
use schematic_macros::*;
// 定义一个Schema结构体
#[derive(Schema)]
struct UserSchema {
#[schema(required)]
id: u64,
#[schema(min_length = 3, max_length = 20)]
username: String,
#[schema(format = "email")]
email: String,
#[schema(default = false)]
is_admin: bool,
#[schema(nested)]
profile: ProfileSchema,
}
// 嵌套的Schema结构体
#[derive(Schema)]
struct ProfileSchema {
#[schema(min_length = 0, max_length = 500)]
bio: Option<String>,
#[schema(min = 13, max = 120)]
age: Option<u8>,
}
// 使用过程宏生成验证器
#[derive(Validator)]
#[validator(schema = "UserSchema")]
struct UserValidator;
fn main() {
let user_data = json!({
"id": 123,
"username": "john_doe",
"email": "john@example.com",
"profile": {
"bio": "Rust developer",
"age": 30
}
});
match UserValidator::validate(&user_data) {
Ok(user) => {
println!("Valid user: {:?}", user);
}
Err(errors) => {
println!("Validation errors: {:?}", errors);
}
}
}
完整示例代码
use serde_json::json;
use schematic_macros::{Schema, Validator};
// 用户数据结构定义
#[derive(Debug, Schema)]
pub struct User {
#[schema(required, min = 1)] // ID必须存在且大于0
pub id: u64,
#[schema(required, min_length = 3, max_length = 20)] // 用户名必填,长度3-20
pub username: String,
#[schema(format = "email")] // 必须符合email格式
pub email: String,
#[schema(default = false)] // 默认值为false
pub is_active: bool,
#[schema(default = "user")] // 默认角色为"user"
pub role: String,
#[schema(nested)] // 嵌套验证地址信息
pub address: Address,
}
// 地址数据结构定义
#[derive(Debug, Schema)]
pub struct Address {
#[schema(required)] // 街道必填
pub street: String,
#[schema(required)] // 城市必填
pub city: String,
#[schema(min_length = 5, max_length = 10)] // 邮编长度5-10
pub postal_code: Option<String>,
}
// 生成用户验证器
#[derive(Validator)]
#[validator(schema = "User")]
pub struct UserValidator;
fn main() {
// 测试数据1 - 有效数据
let valid_data = json!({
"id": 1,
"username": "rustfan",
"email": "rust@example.com",
"address": {
"street": "123 Main St",
"city": "Techville",
"postal_code": "12345"
}
});
// 测试数据2 - 无效数据(缺少必填字段)
let invalid_data = json!({
"id": 0, // 无效ID
"username": "rt", // 用户名太短
"email": "not-an-email",
"address": {
"city": "Techville" // 缺少street字段
}
});
println!("--- 验证有效数据 ---");
match UserValidator::validate(&valid_data) {
Ok(user) => println!("验证成功: {:#?}", user),
Err(e) => println!("验证错误: {:#?}", e),
}
println!("\n--- 验证无效数据 ---");
match UserValidator::validate(&invalid_data) {
Ok(user) => println!("验证成功: {:#?}", user),
Err(e) => println!("验证错误: {:#?}", e),
}
}
功能说明
-
Schema定义:通过
#[derive(Schema)]
宏定义数据结构及其验证规则 -
字段验证:支持多种验证规则如:
required
:必填字段min_length
/max_length
:字符串长度限制format
:格式验证(如email)default
:默认值nested
:嵌套结构验证min
/max
:数值范围验证
-
自动验证器生成:通过
#[derive(Validator)]
宏自动生成验证逻辑 -
错误处理:验证失败时返回详细的错误信息
使用场景
- API请求/响应数据验证
- 配置文件验证
- 数据库模型验证
- 表单数据验证
优势
- 声明式验证:通过属性宏定义验证规则,代码简洁
- 类型安全:充分利用Rust的类型系统
- 可扩展:支持自定义验证规则
- 嵌套验证:支持复杂数据结构的验证
- 良好错误信息:验证失败时提供详细的错误信息
许可证
MIT许可证
1 回复
Rust宏代码生成库schematic_macros使用指南
概述
schematic_macros是一个用于自动化Schema构建和过程宏开发的Rust库,它简化了通过宏生成代码的过程,特别适合需要处理复杂数据结构Schema的场景。
主要功能
- 自动化生成数据结构Schema
- 简化过程宏开发
- 提供类型安全的代码生成
- 支持自定义派生宏
安装
在Cargo.toml中添加依赖:
[dependencies]
schematic_macros = "0.1"
基本用法
1. 自动Schema生成
use schematic_macros::Schema;
#[derive(Schema)]
struct User {
id: u64,
username: String,
email: String,
is_active: bool,
}
这会自动为User
结构体生成对应的Schema实现。
2. 自定义Schema属性
#[derive(Schema)]
struct Product {
#[schema(description = "The unique product identifier")]
id: u64,
#[schema(max_length = 100)]
name: String,
#[schema(min = 0)]
price: f64,
#[schema(skip)]
internal_code: String,
}
3. 枚举支持
#[derive(Schema)]
enum OrderStatus {
Pending,
Processing,
Shipped,
Delivered,
Cancelled,
}
高级用法
1. 自定义派生宏
use schematic_macros::schema_proc_macro;
#[schema_proc_macro]
pub fn generate_serializer(input: TokenStream) -> TokenStream {
// 自定义代码生成逻辑
// ...
}
2. 组合使用
#[derive(Schema, Debug, Clone)]
struct Config {
#[schema(default = "localhost")]
host: String,
#[schema(default = 8080)]
port: u16,
#[schema(default = true)]
logging: bool,
}
实际示例
数据库模型自动生成
#[derive(Schema)]
struct DatabaseModel {
#[schema(primary_key)]
id: u64,
created_at: DateTime<Utc>,
#[schema(index)]
user_id: u64,
data: JsonValue,
}
// 自动生成的Schema可用于验证输入数据
fn validate_input<T: Schematic>(input: &T) -> Result<(), ValidationError> {
T::schema().validate(input)
}
完整示例demo
// 引入必要的库
use schematic_macros::Schema;
use chrono::{DateTime, Utc};
use serde_json::Value as JsonValue;
// 定义一个用户模型
#[derive(Schema, Debug)]
struct User {
#[schema(description = "用户唯一ID", min = 1)]
id: u64,
#[schema(max_length = 50)]
username: String,
#[schema(email_validation = true)] // 假设支持邮箱验证
email: String,
#[schema(default = true)]
is_active: bool,
#[schema(skip)] // 跳过Schema生成
secret_token: String,
}
// 定义订单状态枚举
#[derive(Schema)]
enum OrderStatus {
#[schema(description = "订单待处理")]
Pending,
#[schema(description = "订单处理中")]
Processing,
Shipped,
Delivered,
Cancelled,
}
// 配置结构体示例
#[derive(Schema, Debug, Clone)]
struct AppConfig {
#[schema(default = "127.0.0.1")]
server_host: String,
#[schema(default = 3000, min = 1024, max = 65535)]
server_port: u16,
#[schema(default = true)]
debug_mode: bool,
#[schema(skip)]
api_key: String,
}
fn main() {
// 使用自动生成的Schema验证数据
let user = User {
id: 1,
username: "testuser".to_string(),
email: "test@example.com".to_string(),
is_active: true,
secret_token: "abc123".to_string(),
};
// 这里假设有验证方法
// if let Err(e) = User::schema().validate(&user) {
// eprintln!("Validation error: {:?}", e);
// }
println!("User schema example works!");
// 配置示例
let config = AppConfig {
server_host: "localhost".to_string(),
server_port: 8080,
debug_mode: false,
api_key: "secret".to_string(),
};
println!("Config schema example works!");
}
注意事项
- 确保在Rust 2018或更高版本中使用
- 复杂类型可能需要手动实现某些trait
- 宏展开错误可能需要查看展开后的代码进行调试
schematic_macros通过减少样板代码显著提高了开发效率,特别适合需要处理多种数据Schema的大型项目。