You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在macro_rules中无元变量实现多层数组类型的递归处理?

解决多层数组类型的宏定义问题

要处理int[][]这类多层数组类型,核心是通过递归宏调用逐层剥离数组标记[],每次将内层类型包裹为数组,直到处理完所有嵌套层级。

修改后的完整宏代码

macro_rules! ty {
    // 处理任意层数的数组:递归剥离一层[],包裹内层类型后继续处理剩余[]
    ($inner:tt $([])+) => {
        $crate::types::expr::Type::Array($crate::types::expr::TypeArray {
            item: Box::new(ty!($inner $([])*)),
        })
    };
    (_ []) => {
        $crate::types::expr::Type::Array(TypeArray { .. })
    };
    (int) => {
        $crate::types::expr::Type::Primitive($crate::types::expr::TypePrimitive::Int)
    };
    (bool) => {
        $crate::types::expr::Type::Primitive($crate::types::expr::TypePrimitive::Bool)
    };
    (*) => {
        $crate::types::expr::Type::Any
    };
    (()) => {
        $crate::types::expr::Type::Unit
    };
    ( { $e: expr } ) => {
        $e
    };
}

关键逻辑说明

  • 新增的($inner:tt $([])+)分支匹配至少一个数组标记的情况:
    1. $([])+捕获所有连续的[],$([])*保留当前层之外的剩余[]
    2. 递归调用ty!($inner $([])*),剥离当前层数组标记后继续处理内层类型+剩余数组标记
    3. 每次递归都会将内层类型包裹为Type::Array,直到所有[]处理完毕,最终匹配到基础类型分支

示例效果

调用ty!(int[][])时,宏会展开为:

Type::Array(TypeArray {
    item: Box::new(Type::Array(TypeArray {
        item: Box::new(Type::Primitive(TypePrimitive::Int)),
    })),
})

内容的提问来源于stack exchange,提问作者laptou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:56:07