appendix Exercise solutions

Chapter 2

  1. Fill in the question marks (???), and make the following declarative macro compile.

This is one possible solution. ty seems most appropriate, though ident—for example—would also work:

macro_rules! hello_world {
    ($something:ty) => {
        impl $something {
            fn hello_world(&self) {
                println!("Hello world!")
            }
        }
    };
}

struct Example {}
hello_world!(Example);

fn main() {
    let e = Example {};
    e.hello_world();
}
  1. 2. In our first declarative macro example, we use expr in some of our matches. But that was not our only option. Try to replace that with literal, tt, ident, or ty. Which ones work? Which don’t? Do you understand why?

literal will work because we are passing in literal values (e.g., my_vec!(1, ...

Get Write Powerful Rust Macros now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.