- Hands-On Data Structures and Algorithms with Rust
- Claus Matzinger
- 288字
- 2021-07-02 14:11:41
Macros
Another aspect of Rust is the ability to do metaprogramming—basically programming programming—using macros! Macros are expanded in Rust code before compilation, which gives them more power than a regular function. The generated code can, for instance, create functions on the fly or implement traits for a structure.
These pieces of code make everyday life a lot easier by reducing the need to create and then initialize vectors, deriving the ability to clone a structure, or simply printing stuff to the command line.
This is a simplified example for the declarative vec![] macro provided in the Rust Book (second edition, Appendix D):
#[macro_export]
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$( temp_vec.push($x); )*
temp_vec
}
};
}
Declarative macros work on patterns and run code if that pattern matches; the previous example matches 0 - n expressions (for example, a number, or a function that returns a number) and inserts temp_vec.push(...) n times, iterating over the provided expressions as a parameter.
The second type, procedural macros, operate differently and are often used to provide a default trait implementation. In many code bases, the #[derive(Clone, Debug)] statement can be found on top of structures to implement the Clone and Debug traits automatically.
Later in this chapter, we are going to use a structure, FileName, to illustrate reference counting, but for printing it to the command line using the debug literal "{:?}", we need to derive Debug, which recursively prints all members to the command line:
#[derive(Debug)]
struct FileName {
name: Rc<String>,
ext: Rc<String>
}
The Rust standard library provides several macros already, and by creating custom macros, you can minimize the boilerplate code you have to write.
- 大規(guī)模數(shù)據(jù)分析和建模:基于Spark與R
- Oracle RAC 11g實(shí)戰(zhàn)指南
- Learning JavaScriptMVC
- 云計(jì)算服務(wù)保障體系
- 商業(yè)分析思維與實(shí)踐:用數(shù)據(jù)分析解決商業(yè)問(wèn)題
- 區(qū)塊鏈:看得見(jiàn)的信任
- 數(shù)亦有道:Python數(shù)據(jù)科學(xué)指南
- 大數(shù)據(jù)架構(gòu)和算法實(shí)現(xiàn)之路:電商系統(tǒng)的技術(shù)實(shí)戰(zhàn)
- Power BI商業(yè)數(shù)據(jù)分析完全自學(xué)教程
- SAS金融數(shù)據(jù)挖掘與建模:系統(tǒng)方法與案例解析
- 大數(shù)據(jù)與機(jī)器學(xué)習(xí):實(shí)踐方法與行業(yè)案例
- 大數(shù)據(jù)時(shí)代系列(套裝9冊(cè))
- Unity Game Development Blueprints
- 云工作時(shí)代:科技進(jìn)化必將帶來(lái)的新工作方式
- 量化投資:交易模型開(kāi)發(fā)與數(shù)據(jù)挖掘