DEV Community

Cover image for How to operator overload in Rust.
Will
Will

Posted on

How to operator overload in Rust.

In Rust, types that have certain traits implemented for them are able to be added, subtracted, multiplied, divided, and much more from each other.

In order to operator overload custom types one must implement these traits for their types.

The traits in question come from the standard library at std::ops::*; and can be implemented by doing the following...

First let's create two structs that we can use.

struct Foo(i32);
struct Bar(i32);
Enter fullscreen mode Exit fullscreen mode

Don't forget to use the traits from the standard library.
(You do not have to use them but for convenience I will import them)

use std::ops::{Add};

struct Foo(i32);
struct Bar(i32);
Enter fullscreen mode Exit fullscreen mode

For the purposes of this I will only show adding. After you learn adding the rest should be easy to implement.

Next let's implement these traits that we just imported for our structs.

impl Add<Bar> for Foo {
   /// Todo
}
Enter fullscreen mode Exit fullscreen mode

Above you can see how we implemented Add for the struct Foo + Bar. Now we just have to add the functionality.

impl Add<Bar> for Foo {
    type Output = i32;
    fn add(self, b: Bar) -> i32 {
        self.0 + b.0
    }
}
Enter fullscreen mode Exit fullscreen mode

That is all for adding now to see how it works.

The first thing that might look odd is the type Output, this is simply because if you have a trait and you want the implementor to be able to add any return type to a function within the trait you have to set the return type to a type you create that the implementor can then go and change.

The other thing that might seem odd is that we are creating a function called add, add is already defined within the Add trait, we are simply adding new code to the inside of it so that it works for out type, to do that we have to create the function within our scope.

Let's see if it works now!

fn main() {
    let f = Foo(10);
    let b = Bar(20);
    println!("{}", f + b);
}
Enter fullscreen mode Exit fullscreen mode

Now when you cargo r your program you should get an output of 30!

That is how you operator overload in Rust.

Top comments (0)