axion_data/dataframe/macros.rs
1/// 创建 DataFrame 的便捷宏
2///
3/// 提供了一种简洁的语法来创建 DataFrame,支持多种使用模式。
4///
5/// # 语法
6///
7/// - `df!("列名": 类型 => 数据, ...)` - 带显式类型声明
8/// - `df!("列名" => 数据, ...)` - 自动类型推断
9/// - `df!()` - 创建空 DataFrame
10///
11/// # 示例
12///
13/// ```rust
14/// use axion::df;
15///
16/// // 类型推断
17/// let df1 = df! {
18/// "name" => vec!["Alice", "Bob"],
19/// "age" => vec![25, 30]
20/// }?;
21///
22/// // 显式类型
23/// let df2 = df! {
24/// "id": i32 => vec![1, 2],
25/// "score": f64 => vec![95.5, 87.2]
26/// }?;
27///
28/// // 空 DataFrame
29/// let empty = df!()?;
30/// ```
31///
32/// # 返回值
33///
34/// 返回 `AxionResult<DataFrame>`
35///
36/// # 错误
37///
38/// 当列长度不匹配或存在重复列名时返回错误
39#[macro_export]
40macro_rules! df {
41 // 匹配带显式类型的所有列
42 ($($name:literal : $type:ty => $data:expr),+ $(,)?) => {
43 (|| -> $crate::error::AxionResult<$crate::dataframe::DataFrame> {
44 let mut cols: Vec<Box<dyn $crate::series::SeriesTrait>> = Vec::new();
45 $(
46 // 使用提供的显式类型
47 let series = $crate::series::IntoSeriesBox::<$type>::into_series_box($data, $name.to_string())?;
48 cols.push(series);
49 )+
50 $crate::dataframe::DataFrame::new(cols)
51 })()
52 };
53
54 // 匹配不带显式类型的所有列(使用类型推断)
55 ($($name:literal => $data:expr),+ $(,)?) => {
56 (|| -> $crate::error::AxionResult<$crate::dataframe::DataFrame> {
57 let mut cols: Vec<Box<dyn $crate::series::SeriesTrait>> = Vec::new();
58 $(
59 // 依赖类型推断
60 let series = $crate::series::IntoSeriesBox::into_series_box($data, $name.to_string())?;
61 cols.push(series);
62 )+
63 $crate::dataframe::DataFrame::new(cols)
64 })()
65 };
66
67 // 匹配空 DataFrame 定义(可选)
68 () => {
69 (|| -> $crate::error::AxionResult<$crate::dataframe::DataFrame> {
70 $crate::dataframe::DataFrame::new(Vec::new())
71 })()
72 };
73}