Rust 中的宏和函数有什么区别? [英] What is the difference between macros and functions in Rust?

查看:54
本文介绍了Rust 中的宏和函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引自 Rust 博客:

最后一件事:Rust 的宏与 C 宏有很大的不同,如果你用过的话

One last thing to mention: Rust’s macros are significantly different from C macros, if you’ve used those

Rust 中的宏和函数有什么区别?它与 C 有何不同?

What is the difference between macros and function in Rust? How is it different from C?

推荐答案

继续阅读文档,特别是 宏章节

Keep on reading the documentation, specifically the chapter on macros!

宏在编译时执行.它们通常会扩展为编译器需要进一步处理的新代码段.

Macros are executed at compile time. They generally expand into new pieces of code that the compiler will then need to further process.

对我来说最大的不同是 Rust宏是hygenic.这本书有一个例子解释了卫生可以预防什么,还说:

The biggest difference to me is that Rust macros are hygenic. The book has an example that explains what hygiene prevents, and also says:

每个宏扩展都发生在不同的语法上下文"中,并且每个变量都使用引入它的语法上下文进行标记.

Each macro expansion happens in a distinct ‘syntax context’, and each variable is tagged with the syntax context where it was introduced.

它使用这个例子:

例如,这个 C 程序打印 13 而不是预期的 25.

For example, this C program prints 13 instead of the expected 25.

#define FIVE_TIMES(x) 5 * x

int main() {
    printf("%d\n", FIVE_TIMES(2 + 3));
    return 0;
}

除此之外,Rust 宏

Beyond that, Rust macros

  • 可以与编译后的代码一起分发
  • 可以在参数计数中重载
  • 可以匹配大括号、括号或逗号等语法模式
  • 可能需要重复输入模式
  • 可以递归
  • 在语法级别操作,而不是文本级别

这篇关于Rust 中的宏和函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆