| Crates.io | comptime-if |
| lib.rs | comptime-if |
| version | 0.1.1 |
| created_at | 2026-01-25 01:57:17.458162+00 |
| updated_at | 2026-01-25 04:53:21.358897+00 |
| description | Compile-time `if` procedural macro for Rust |
| homepage | |
| repository | https://github.com/sevenc-nanashi/comptime-if |
| max_upload_size | |
| id | 2067920 |
| size | 24,555 |
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:
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;
The syntax for the comptime_if! macro is as follows:
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)( 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.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.");
}
}