DEV Community

Anil Kumar Khandei
Anil Kumar Khandei

Posted on

Operator Overloading in Rust

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

struct Point{
        x:i32,
        y:i32
    };
Enter fullscreen mode Exit fullscreen mode

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,
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

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;     
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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)
        }
    }
Enter fullscreen mode Exit fullscreen mode

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
        }
    }
Enter fullscreen mode Exit fullscreen mode

I hope this saves your day while learning rust.

Latest comments (2)

Collapse
 
bretthancox profile image
bretthancox

You access the input and self Strings by index. Is that because your MyString struct is a tuple?

Collapse
 
anilkhandei profile image
Anil Kumar Khandei

Yup a tuple struct.