In a library one may want to restrict implementations of a trait to be thread safe based on a feature flag. This sometimes involves changing trait inheritance. However, attributes are not allowed on the trait inheritance bounds. A common workaround is to copy the trait:
#[cfg(not(feature = "thread_safe"))]
pub trait MyTrait {
fn foo();
}
#[cfg(feature = "thread_safe")]
pub trait MyTrait: Send + Sync {
fn foo();
}
The duplicated code can be mitigated by using a macro (see below), but this can make the IDE experience suffer. Is there a better way to achieve conditional trait inheritance?
macro_rules! my_trait {
($($bounds:ident),*) => {
pub trait MyTrait where $(Self: $bounds),* {
fn foo();
}
};
}
#[cfg(not(feature = "thread_safe"))]
my_trait!();
#[cfg(feature = "thread_safe")]
my_trait!(Send, Sync);