官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 辽源市| 唐海县| 德兴市| 东辽县| 蒙山县| 威宁| 唐海县| 永安市| 海口市| 怀来县| 莆田市| 洛隆县| 泾阳县| 前郭尔| 容城县| 古交市| 古交市| 塔河县| 台安县| 乌海市| 井陉县| 玉林市| 庐江县| 连州市| 永定县| 绥化市| 深泽县| 修文县| 宜宾县| 讷河市| 波密县| 屯昌县| 敦化市| 塔城市| 罗田县| 乌兰察布市| 高平市| 施秉县| 稻城县| 昆山市| 会东县|