# comptime_if
[](https://docs.rs/comptime-if)
[](https://crates.io/crates/comptime-if)
[](https://crates.io/crates/comptime-if)
Simple compile-time conditional code inclusion for Rust macros.
This crate provides the `comptime_if!` macro, which allows you to include or exclude code blocks
based on compile-time boolean expressions.
This macro is useful for `macro_rules!` macros that accepts boolean parameters, like this:
```rust
mod test_module {
use comptime_if::comptime_if;
macro_rules! export {
($struct_name:ident, $($key:ident = $value:expr),* $(,)?) => {
// `export = true` before `$(key = $value),*` works as the default value
comptime_if! {
if export where (export = true, $($key = $value),*) {
pub struct $struct_name;
} else {
struct $struct_name;
}
}
};
// You might want to provide a default for the case when no key-value pairs are given
($struct_name:ident) => {
export!($struct_name, );
};
}
// Expands to `pub struct MyStruct;`
export!(MyStruct, export = true);
}
// `MyStruct` is publicly accessible
use test_module::MyStruct;
```
# Syntax
The syntax for the `comptime_if!` macro is as follows:
```rust,ignore
comptime_if! {
if (<condition>) where (<variable assignments>) {
<code block if condition is true>
} else {
<code block if condition is false>
}
}
```
- `<condition>`: A boolean expression that can include variables, logical operators and parentheses.
You can omit the parentheses if the condition is a single variable or a negation of a single variable.
Supported operators are:
- `&&`, `&` (logical AND)
- `||`, `|` (logical OR)
- `^` (logical XOR)
- `==` (logical EQUAL)
- `!=` (logical NOT EQUAL)
- `!` (logical NOT)
- Parentheses `(` and `)` for grouping
- `<variable assignments>`: A comma-separated list of variable assignments in the form
`<variable> = <boolean value>`. Multiple assignments to the same variable will use the last
assignment.
# Example
```rust
use comptime_if::comptime_if;
comptime_if! {
if condition where (condition = true) {
println!("This code is included because condition is true.");
} else {
compile_error!("This code is excluded.");
}
}
comptime_if! {
if (a && (b || !c)) where (a = true, b = false, c = false) {
println!("This code is included because the condition evaluates to true.");
} else {
compile_error!("This code is excluded.");
}
}
```