Varying trait inheritance based on features

Hi all,

So, I am developing a library and I would like the feature parallel to be optional. If it is not enabled, then I will default to std::rc::Rc<>, but when it is activated I will use std::sync::Arc<>. Now, I have a trait somewhere that needs to be extended by Sync and Send in one case but not in the other. I wonder if it is possible to use conditional compilation to handle this...?

// My initial thought was this, which I know is experimental... I would like to avoid 
// experimental things.

#[cfg(feature = "parallel")]
trait Aux = Intersect + Sync + Send;
#[cfg(not(feature = "parallel"))]
trait Aux = Intersect;

pub trait Sampleable : Aux {
        //... fill this 
}

Any hints on this?

Thanks in advance!

Instead of using a trait alias, you can just define and blanket-impl a real trait:

#[cfg(feature = "parallel")]
trait Aux: Intersect + Sync + Send {}

#[cfg(feature = "parallel")]
impl<T: Intersect + Sync + Send> Aux for T {}

#[cfg(not(feature = "parallel"))]
trait Aux: Intersect {}

#[cfg(not(feature = "parallel"))]
impl<T: Intersect> Aux for T {}
1 Like

But that will require me to write the same trait twice, won't it? It is kind of painful and can introduce errors later on.

Any other suggestions?

Or, Is there a benefit of using Rc vs Arc? (that is the main difference introduced by the parallel feature.

You only have to write literally this much code – I thought the very point of the Aux trait was to encapsulate this difference only, and that the bulk of the real code resides in Sampleable. If that is not the case, you can always introduce an additional trait between the two.

1 Like

Rc is cheaper to clone than Arc ( since it doesn't have to go to shared memory rather than local CPU cache memory ).

[ What I have found useful, not sure if you could call it a design pattern, is to have local Rc pointers which point to a struct which has the actual Arc data in it ( and can therefore be shared between threads ). There is a lot of Rc cloning, but Arc clones are infrequent. ]

1 Like

This works fantastically! I don't know why, exactly, but it does.

The only caveat is that, if I want to export my Sampleable trait, I also need to export the Aux one. I guess this will not be an issue, though.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.