知识卡片
编译期生成代码的宏
宏在编译期间扩展成代码,能解析不同数量或形状的记号,也能生成新的 trait 实现。函数在运行时接收符合签名的值,与宏相比,更适合普通输入到输出的复用。只有确实需要改变输入语法、生成声明等能力时,宏增加的间接性和维护成本才有相应收益。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · Macros
原书出处 · 1 处
- 高级特性 Macros · 查看原书依据
A function signature must declare the number and type of parameters the function has. Macros, on the other hand, can take a variable number of parameters: we can call println!("hello") with one argument or println!("hello {}", name) with two arguments. Also, macros are expanded before the compiler interprets the meaning of the code, so a macro can, for example, implement a trait on a given type.
参考来源
- 位置:《The Rust Programming Language(第2版)》第19章 高级特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c19.xhtml`,块 0325)
- 结论依据:原文将宏的可变参数与编译前展开和函数的固定参数及运行时调用对照。
- 原始内容:A function signature must declare the number and type of parameters the function has. Macros, on the other hand, can take a variable number of parameters: we can call println!("hello") with one argument or println!("hello {}", name) with two arguments. Also, macros are expanded before the compiler interprets the meaning of the code, so a macro can, for example, implement a trait on a given type.