10

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
w.brian
  • 16,296
  • 14
  • 69
  • 118

1 Answers1

19

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366