code shogan
code shogan

Reputation: 839

Trait bound on generic trait

I want to know how to create a generic function bound to a generic trait.

In this example I have chosen BitXor. The declaration of std::ops::BitXor is BitXor<RHS, Result>.

So if we have our function:

fn e<T: BitXor>(m:T, k:T) -> T {
    m ^ k
}

The compiler will complain:

error: Wrong number of type arguments: expected 2 but found 0.

So I tried:

fn e<T: BitXor<U, V>, U, V>(m:T, k:T) -> T {
    m ^ k
}

But get the rather confusing error:

Mismatched types: expected `U` but found `T` (expected type parameter but found type parameter).

Any solution?

Upvotes: 2

Views: 2366

Answers (1)

Francis Gagn&#233;
Francis Gagn&#233;

Reputation: 65897

Here's the full definition of the BitXor trait:

#[lang="bitxor"]
pub trait BitXor<RHS, Result> {
    fn bitxor(&self, rhs: &RHS) -> Result;
}

Notice how the rhs operand is of type &RHS. In your case, RHS is U (because you have BitXor<U, V>), yet k, which you pass as rhs through the ^ operator, is of type T. Likewise, the result is of type Result, which in your case is V, yet your function returns T.

There are two possible signatures, depending on your use case:

fn e<T: BitXor<U, V>, U, V>(m: T, k: U) -> V {
    m ^ k
}

In this one, we use more type parameters to get maximum genericity.

fn e<T: BitXor<T, T>>(m: T, k: T) -> T {
    m ^ k
}

In this one, we sacrifice genericity to restrict all values to be of the same type.

Upvotes: 3

Related Questions