Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally derive based on feature flag [duplicate]

Tags:

rust

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 image 451
w.brian Avatar asked Feb 04 '17 22:02

w.brian


1 Answers

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.

like image 164
Shepmaster Avatar answered Oct 20 '22 00:10

Shepmaster