[Rust] Write macro

Define a macro and use it:

macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    };
}

fn main() {
    my_macro!();
}

 

Notice that you have time define macrobefore main function. Otherwise it doesn't work.

 

Expose a macro from module:

mod macros {
    #[macro_export]
    macro_rules! my_macro {
        () => {
            println!("Check out my macro!");
        };
    }
}

fn main() {
    my_macro!();
}

We need to add attribute #[macro_export], in order to make it work.

 

Arms:

The macro my_macro is defined with two "arms", each of which matches different patterns of input and associates those patterns with specific code blocks.

There are two arms in following code:

macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    }; // ; is important
    ($val:expr) => { //:expr the val should be an expersion
        println!("Look at this other macro: {}", $val);
    }; // ; is important
}

fn main() {
    my_macro!();
    my_macro!(7777);
}

 

posted @   Zhentiw  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-02-27 [Typescript] The partial Inference Problem
2019-02-27 [Functional Programming] Use Task/Async for Asynchronous Actions
2019-02-27 [Functional Programming] Working with two functors(Applicative Functors)-- Part2 --liftAN
2018-02-27 [CSS3] Create Dynamic Styles with CSS Variables
2017-02-27 [Flow] The Fundamentals of Flow
2017-02-27 [Angular] Some performance tips
2017-02-27 [Ramda] Rewrite if..else with Ramda ifElse
点击右上角即可分享
微信分享提示