Operator Overloading in Rust

8 2

I am learning operator overloading in Rust. There is this basic example in the programming book:

struct Point{
        x:i32,
        y:i32
    };

Then implement the add trait over the Point type to be able to add 2 instances of the point type like so:

impl Add<Point> for Point{
        type Output=Point;
        fn add(self, point:Point)->Self::Output{
            Point{
                x:self.x+point.x,
                y:self.y+point.y,
            }
        }
    }

Now we can add 2 points using the below statement:

let point_a=Point{
x:30,
y:40
}

let point_b=Point{
x:50,
y:60
}
point_c=point_a+point_b;     

So far so good right? Now can you tell me how to implement the same for String type or for the string literal &str, well it took me a day to figure out how to do that-

First create a new Type using the base String type-

struct MyString(String);

Then implement the Add trait over the custom type like this-

impl Add<MyString> for MyString{
        type Output= MyString;
        fn add(self,input:MyString)->Self::Output{
            let mut own_str=self.0.to_string();
            let input_str=input.0.to_string();
            own_str.push_str(&input_str);
            MyString(own_str)
        }
    }

once you understand the above, you can try re-writing the same like this, in a fewer lines of code-

impl Add<MyString> for MyString{
        type Output= MyString;
        fn add(self,input:MyString)->Self::Output{
            self.0.to_string().push_str(&input.0.to_string());
            self
        }
    }

I hope this saves your day while learning rust.

Build with &
Edit dev-to-clone-nuxt Edit dev-to-clone-nuxt