Conditional supertrait compilation with features

You can't add a #[cfg] attribute to part of a where-clause because Rust's syntax wasn't designed that way.

I'd also recommend against this pattern in general. Features are meant to compose and be purely additive, but imagine a situation like this...

  • Crate A implements MyTrait on some type Foo without with-trait1
  • Crate B adds A as a dependency
  • Crate B uses A, relying on the fact that Foo: MyTrait
  • Crate B enables the with-trait1 feature, adding extra requirements for MyTrait... Requirements that crate A doesn't fulfill because it didn't enable the with-trait1 feature.

That said, you can implement it by adding a #[cfg] to the entire trait definition.

#[cfg(feature = "with-trait1")]
pub trait MyTrait: Copy + Trait1 + Trait2 { ... }

#[cfg(not(feature = "with-trait1"))]
pub trait MyTrait: Copy + Trait2 { ... }

// or if the body of `MyTrait` is long and you don't want to
// repeat yourself, pull the requirements out into an 
// intermediate trait.

#[cfg(feature = "with-trait1")]
pub trait Deps: Copy + Trait1 + Trait2 {  }

#[cfg(not(feature = "with-trait1"))]
pub trait Deps: Copy + Trait2 { }

pub trait MyTrait: Deps { ... }
2 Likes