How to override a macro?

In C ++, you can define and override a macro. For example, it is common practice in video games to override the registration macro to Release in the Nothing mode. This ensures that the code disappears completely, which helps with performance.

Is there any way to do this in Rust?

+4
source share
2 answers

Basically you can:

macro_rules! log_if_dbg { (...) => (if cfg!(debug_assertions) { /* do logging */ }) } 

This is how the debug_assert! macro is debug_assert! . Doc says:

Unlike assert !, debug_assert! statements are only included in the optimized assembly by default. Optimized build will lower all debug_assert! if -C-debug statements are passed to the compiler. This makes debug_assert! useful for checks, which are also an expensive presence in the release build, but may be useful during development.

This is the same as your situation, only for assert, not logging. Looking at the source :

 macro_rules! debug_assert { ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); }) } 

This was also briefly discussed in the Rust users forum, where the summary is that cfg(debug_assertions) is a way to check if we are in debug mode.

I don't know how stable cfg(debug_assertions) .

+6
source

You should use conditional compilation attributes:

 #[cfg(feature = "debugging")] macro_rules! log { () => { println!("Debugging") } } #[cfg(not(feature = "debugging"))] macro_rules! log { () => { } } fn main() { log!(); } 

Here you can use Cargo "features" to provide a compile-time argument that switches the debugging implementation.

However, in this case there is no need to use macros:

 #[cfg(feature = "debugging")] fn log() { println!("Debugging") } #[cfg(not(feature = "debugging"))] fn log() {} fn main() { log(); } 

I would very much trust the optimizer to create the same code in this case.

+3
source

All Articles