Rust宏中ident与ty匹配冲突问题咨询
Rust宏分支匹配优先级问题示例
macro_rules! thisis { ($t: ty) => { println!("this is a type") }; ($t: ident) => { println!("this is an ident") }; } fn main() { const variable: i32 = 32; thisis!(i32); thisis!(variable); }
在上述示例中,两次调用thisis!宏均打印“this is a type”。这是因为Rust的macro_rules!宏采用按顺序匹配分支的规则:当输入同时符合多个分支的匹配模式时,只会匹配最先定义的分支。这里variable作为标识符(ident),同时也能被ty模式匹配(宏匹配中标识符可被解析为类型名),因此第二个调用也命中了第一个分支,而非预期的第二个分支。
内容的提问来源于stack exchange,提问作者Nour-eddine Taleb
相关产品推荐
相关产品推荐

