#C++ Preprocessors in Rust?
5 messages · Page 1 of 1 (latest)
We don't have a C preprocessor, but you can do this. Since Rust tends to prefer functions whenever possible, you can write
#[cfg(debug_assertions)] //cfg = conditional compilation flag
fn log<T: Debug>(elem: T) {
println!("{elem:?}");
}
#[cfg(not(debug_assertions))]
fn log<T: Debug>(elem: T) {}
```If you want to use macros instead, they work the same, you can put `cfg` on them too.
If you have a complex cfg chain, use the cfg-if crate, the "basic" syntax can be unwieldy
Thank you!
Can you write the same example with macros?
I want to understand how you do it in both ways 🙂
#[cfg(debug_assertions)]
macro_rules! log {
($e:expr) {
println!("{:?}", $e),
}
}
#[cfg(not(debug_assertions))]
macro_rules! log {
($e:expr) {}
}