pub_if
A Rust procedural macro that conditionally makes struct fields public based on cfg attributes.
syn-free implementation using only proc_macro APIs.
Usage
Add the #[pub_if(...)] attribute to a struct to generate two versions:
- One with
#[cfg(...)]where all fields are public - One with
#[cfg(not(...))]where fields retain their original visibility
use pub_if;
This expands to:
Features
- Fields already marked
pubremain public in both versions - Supports generic types
- Works with any cfg condition (features, target_os, etc.)
- Implemented without the
syncrate using onlyproc_macroAPIs
Examples
Mixed visibility
When the feature is enabled, both fields are public.
When disabled, only public_setting remains public.
Testing
The project includes compile-time tests using trybuild to verify that:
- Fields are public when the cfg condition is enabled
- Fields remain private when the cfg condition is disabled
- Fields already marked
pubstay public in both cases
# Run tests without feature (verifies private fields are not accessible)
# Run tests with feature (verifies all fields become public)