MOCKBA
November 18, 2024, 1:32am
1
There is a simple syntactical solution I can't figure out. For example, I have enum with a default value as below:
pub enum Compression {
#[cfg(not(feature = "deflate"))]
#[default]
Store,
Shrink,
Reduction1,
Reduction2,
Reduction3,
Reduction4,
Implode,
#[cfg(feature = "deflate")]
#[default]
Deflate,
Deflat64,
BZIP2,
LZMA,
PPMd ,
}
I want to make a default value in dependency that a certain feature is set. However
#[cfg
directive get applied to the next enum value and ignores #[default]. How can I make the default conditional?
I tried this and it worked, so perhaps you have some other issue. When the feature is on, Deflate
is the default, and when it is off, Store
is the default. This does remove the non-default variant entirely, though. If you want still include the variants and just change which one is default, you can write them twice.
#[derive(Debug, Default)]
pub enum Compression {
#[cfg(not(feature = "deflate"))]
#[default]
Store,
#[cfg(feature = "deflate")]
Store,
Shrink,
Reduction1,
Reduction2,
Reduction3,
Reduction4,
Implode,
#[cfg(feature = "deflate")]
#[default]
Deflate,
#[cfg(not(feature = "deflate"))]
Deflate,
Deflat64,
BZIP2,
LZMA,
PPMd,
}
It's kind of ugly, though. I'd probably just impl Default
manually at this point.
You should just manually impl it:
impl Default for Compression {
fn default() -> Self {
if cfg!(feature = "deflate") {
Compression::Deflate
} else {
Compression::Store
}
}
}
(something like this, I'm not super familiar w/ cfg stuff)
Hyeonu
November 18, 2024, 1:58am
4
Use cfg_attr
to apply attribute itself conditionally.
7 Likes
Oh, that's a better idea.
#[derive(Debug, Default)]
pub enum Compression {
#[cfg_attr(not(feature = "deflate"), default)]
Store,
Shrink,
Reduction1,
Reduction2,
Reduction3,
Reduction4,
Implode,
#[cfg_attr(feature = "deflate", default)]
Deflate,
Deflat64,
BZIP2,
LZMA,
PPMd,
}
1 Like
MOCKBA
November 18, 2024, 2:28am
6
Awesome, it worked as planned. Thanks to all for the help.