How to implement a trait that can perform exponentiation?

In python, if I want to calculate an exponent of a number then I can do as follows.

a = 3
b = a ** 2

Now someone can implement this for their class by using def __pow__(self, exponent):.

Can I perform something similar in Rust?

You can find the traits for Rust’s overloadable operators in std::ops, but they don’t include one for exponentiation. I suppose you could use BitXor (^), but I can’t recommend it— You will confuse a lot of people and it probably doesn’t have the precedence you want.

3 Likes

I believe, you mean BitXor over here.

Yes; corrected.

The num-traits crate has a Pow trait you can use, similar to the ones in std::ops. It does not come with an operator like ** but can be used as a generic bound and implemented on your own types.

2 Likes

Thanks, @leob. I'll use that. :slight_smile:

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.