Can I have where clauses that appear only when we have a feature?

Suppose I want to write a function that is generic on the numeric integer type:

pub fn add_modulo<T, U, M>(t: T, u: U, m: M) -> T {
    //
}

but I want to do the fast version of it later, and for now I'll just convert the numbers into big integer and do the stuff:

pub fn add_modulo_slow<T, U, M>(t: T, u: U, m: M) -> T {
    let t = BigInt::from(t);
    let u = BigInt::from(u);
    let m = BigIng::from(m);
    ((t+u)%m).into()
}

If I want to put this inside add_modulo, I have to do like this:

pub fn add_modulo<T, U, M>(t: T, u: U, m: M) -> T 
where BigInt: From<T>

{
    //temporary slow call, to be replaced by fast implementation later
    add_modulo_slow(t,u,m)
}

this pollutes the chain of caller functions that call this function, but I wanted BigInt to be a completely optional feature, so it shouldn't even be there when I try to compile without the feature.

What would be a better option here? Can I have a where clause that only appears in a feature, without having to have 2 versions of the function, each one activated per feature?

I’m having a hard time understanding the context of your problem in two ways:

  1. What kind of trait bounds does add_modulo still have when there isn’t the BigInt: From<…> bound(s)? With a completely generic type like that it isn’t going to be able to do anything. Or is this just “simplified” code, and your real example looks different?

  2. If the “slow implementation” is only temporary / is supposed to be replaced later, why do you want to make it available with a feature flag? This doesn’t sound too much like “this is going to be replaced” to me and more like “this is going to be an alternative to chose from”. Finally, having a feature add bound in Rust is not allowed w.r.t. semantic versioning. I mean, you can “technically” do it (i.e. the compiler will not prevent it), but features are supposed to be additive and not break anything when added. After all, if any crate in the dependency tree needs some feature of crate foo, then all crates depending on foo will get the version of foo with that feature enabled, so things could easily break if they aren’t expecting the BigInt: From<…> bounds.

1 Like

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.