Macros Flashcards

1
Q

What are the differences between functions and macros?

A
  1. 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.
  2. Macros are expanded before the compiler interprets the meaning of the code (hence can implement a trait, for example), while a function only gets called at runtime.
  3. Macros definitions are generally more difficult to read, understand and maintain than function definitions.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What types of procedural macros are there?

A
  1. Custom #[derive] macros - that specify code added with the “derive” attribute used on struct and enums
  2. Attribute-like macros - that define custom attributes usable on any item
  3. Function-like macros that look like function calls but operate on the tokens specified as their argument.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Use macro_rules! construct to define the vec! macro (simplified version, without pre-allocating the correct amount of memory up front)

A
#[macro_export]
macro_rules! vec {
  ( $( $x:expr ),* ) => {
    {
      let mut temp_vec = Vec::new();
      $(
        temp_vec.push($x);
        )*
        temp_vec
    }
  };
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does the #[macro_export] annotation indicate?

A

The #[macro_export] annotation indicates that this macro should be made available whenever the crate in which the macro is defined is brought into scope. Without this annotation, the macro can’t be brought into scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
What $($x:expr),* means in this macro implementation?
macro_rules! vec {
  ( $( $x:expr ),* ) => {
  ...
  }
}
A

$x:expr matches any Rust expression and gives the expression the name$x.
The comma following $() indicates that a literal comma separator character could optionally appear after the code that matches the code in $(). The * specifies that the pattern matches zero or more of whatever precedes the *.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly