I want to add a feature to my crate that will optionally make certain structs serializable, and in particular, I want to use Serde's custom derive macros. The Serde dependencies are optional and extern crate
declarations are conditionally included behind the feature. Consider the following:
#[derive(Eq, PartialEq, Serialize)]
struct MyStruct {
a: u8,
b: u8
}
With the feature flag enabled, it all works fine. With it disabled, I get this warning:
error: '#[derive]' for custom traits is not stable enough for use. It is deprecated and will be removed in v1.15 (see issue #29644)
Is there a way to conditionally include derived traits? I'm using Rust 1.15 stable.
Should I submit an issue for the error message? It seems misleading.
Like many other pieces of feature-based conditional compilation, use cfg_attr
:
#[cfg_attr(feature = "example", derive(Debug))]
struct Foo;
fn main() {
println!("{:?}", Foo);
}
With this, cargo run
will fail to compile as Debug
is not implemented for Foo
, but cargo run --features example
will compile and run successfully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With