Operator overloading and orphan rule

Greetings everyone

I am trying to learn standard operator overloading and am practicing on my own sample code.

I read that due to Rust orphan rule I am not able to use operator overloading on Rust standard library types such as String.

For example, let us say I want to overload a Shift Left << operator (Shl Trait) on String.
This is impossible in Rust 1.54 because neither Shl Trait nor String is something introduced in my code.
I can understand why this rule exists, this is not my question.

BUT IF I wanted to be able to build something like this using << and >> operators on String data, is this possible?

Something like:

let mystr = "Hello Word!" << 6;

I expect mystr to have "World!" as the result of above pseudo-code, so by shifting the String to Left, I wiped off first 6 characters ("Hello ") and shrunk the result by same 6 characters after shift.

Is this possible with operator overloading using << and >> ?
Does it make sense?

I realize this is artificial, my aim is to learn and understand how to write idiomatic and ergonomic Rust using operator overloading.

Perhaps this is a stupid exercise that I have come up with?

Thank you very much!

This is possible if you create a newtype. It is not possible to do on strings themselves because of the orphan rule, as you've noted.

2 Likes

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.