WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Intermediate · question 29 of 100

What is a macro in Rust, and how do you create one? Provide a simple example.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, a macro is a shorthand syntax that allows you to define new syntax constructs that expand into larger code snippets at compile time. Macros are a powerful feature of Rust that enable the creation of domain-specific languages, reduce code repetition, and improve code maintainability.

To create a macro in Rust, you use the ‘macro_rules!‘ macro. This macro takes a pattern and a expansion rule, and matches the pattern at compile time. When the matched pattern is identified in the code, the expansion rule is executed, resulting in the generated code.

Here is a simple example of a macro that generates a simple ‘println‘ statement:

    macro_rules! greeting {
        ($name:expr) => {
            println!("Hello, {}!", $name);
        };
    }
    
    fn main() {
        greeting!("John"); // expands to println!("Hello, John!");
    }

In this example, the ‘greeting‘ macro takes an expression (in this case, a string literal) as an argument using the ‘$name:expr‘ syntax. The macro expands into the ‘println‘ statement with the provided expression, resulting in the output of "Hello, John!".

Macros can be more complex and powerful than this example, allowing for recursion, conditional logic, and more. They are an essential tool for Rust programmers looking to write more efficient and maintainable code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics