I've been toying around with the cfg annotation, but it seems lackluster from what I've seen. From what I've seen, it has to be prepended to every struct/const/static var/etc that follows that you want the cfg to apply to? It seems rather....not ideal unless there's a way to group them all under one annotation (ie. curly braces, maybe, but that would imply scope as well) I know for statements in code blocks, a simple if cfg!(feature = "foo") { ... } suffices but not sure if there's an annotation equivalent.
If I'm not clear, I'm trying to accomplish in Rust what the following in C/C++ might do:
struct Person {
char *name;
int age;
#ifdef MORE_INFO_SUPPORTED
char* job_title;
#endif
};
You want cfg-if! It provides a macro which does at least some of what you want it to.
cfg_if!{ if #[cfg( feature = "Foo" )]{
/* Conditionally compiled code goes here */
} else if #[cfg( feature = "Bar")] {
/* ... */
}}
The only real downside to the crate in my opinion is that it will nest things twice whenever you want to do conditional compilation and most IDEs will auto-indent accordingly. Personally I use a mix of it for large blocks of code and single line #[cfg] directives for things like single imports.
Another option is to put all your conditional compilation into its own module. Something like:
#[cfg( feature = "Foo" )]
mod foo {
/* Conditionally compiled code goes here */
}
but that only works if your feature is gating a whole bunch of conditional compilation and get frustrated by the extra indentation, think something like platform specific utilities or a compatibility layer into another crate.
EDIT: I'm completely wrong about this, it worked for me earlier in a trait which is a different beast entirely and doesn't really help you.
Maybe try wrapping the conditional values up in their own structure, an enum or tuple. Depending on how involved the optional values are having a struct wrapping them might make them easier to work with
So in declaring a bitflags flag struct for a crate I'm making that implements the Hotline protocol, one such flag struct describes user privilege flags. The way Hotline does it is very weird: depending on endian, the bits of each byte are reversed, but the bytes themselves are not swapped. I used #[cfg(target_endian "...")] ("..." of course being "big" and "little"), but I'm not sure if I was supposed to document it twice?