DEV Community

Cover image for Decorators in Rust
Santhosh Balasa
Santhosh Balasa

Posted on • Updated on

Decorators in Rust

Code:

// Define the macro.
macro_rules! log_function {
    ($f:ident($($arg:expr),*)) => {{
        println!("Calling function: {}", stringify!($f));
        $f($($arg),*)
    }};
}

// Some function for demonstration.
fn add(x: i32, y: i32) -> i32 {
    x + y
}

fn main() {
    // Use the macro.
    let result = log_function!(add(5, 7));
    println!("Result: {}", result);
}
Enter fullscreen mode Exit fullscreen mode

Output:

Calling function: add
Result: 12
Enter fullscreen mode Exit fullscreen mode

Rust may not come with built-in support for Python-esque decorators, but that doesn't mean we can't engineer our own! With the might of Rust's macro system at our disposal, we demonstrate how to craft a Python-style decorator using the log_function! macro.

This above inventive piece of code logs function names just before they spring into action. The add function serves as the stage for this cross-linguistic performance, highlighting the extraordinary fusion of Python's elegant simplicity and Rust's high-octane performance within a single, harmonious codebase.

Top comments (0)