patternrustCritical
Is it possible to conditionally enable an attribute like `derive`?
Viewed 0 times
conditionallypossibleattributelikederiveenable
Problem
I have added a feature in my crate which adds
This code treats everything below
I have tried to wrap it with braces but it gives another error:
Code:
Error:
So how to do this?
serde support. However, I don't quite understand how to use it properly:// #[derive(Debug, Serialize, Deserialize, Clone)] // goes to:
#[derive(Debug, Clone)]
#[cfg(feature = "serde_support")]
#[derive(Serialize, Deserialize)]
pub struct MyStruct;This code treats everything below
cfg(feature) as conditionally compiled, so without my serde_support feature my crate does not have MyStruct also.I have tried to wrap it with braces but it gives another error:
Code:
#[derive(Debug, Clone)]
#[cfg(feature = "serde_support")] {
#[derive(Serialize, Deserialize)]
}
pub struct MyStruct;Error:
error: expected item after attributes
--> mycrate/src/lib.rs:65:33
|
65 | #[cfg(feature = "serde_support")] {
| ^
So how to do this?
Solution
You can use the
It's described in the Rust reference about "conditional compilation":
Will be the same as
cfg_attr(a, b) attribute:#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct MyStruct;It's described in the Rust reference about "conditional compilation":
#[cfg_attr(a, b)]
itemWill be the same as
#[b] item if a is set by cfg, and item otherwise.Code Snippets
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct MyStruct;#[cfg_attr(a, b)]
itemContext
Stack Overflow Q#42551113, score: 185
Revisions (0)
No revisions yet.