简体   繁体   中英

How to overloading operator without using ops::Add trait?

I have some code like this:

trait MyTrait{}

struct MyStruct{}
impl MyTrait for MyStruct{}

i want to implement '+' operator for every struct that implement MyTrait so i tried this

impl<T: MyTrait> std::ops::Add for T
{
...
} 

But i get the error: type parameter `T` must be used as the type parameter for some local type . So now i want to implement '+' operator for every struct that implements MyTrait without using std::ops::Add trait.

This is by design not possible.

The reason is that Rust has the orphan rules which prohibit a crate (you) from implementing traits for types unless at least one of them (either the trait or the type) is defined by that crate (you).

You are trying to implement std::op::Add (a trait defined in another crate, std ) for all types T , some of which are necessarily not defined by you (since any crate can define new types). Therefore, you violate the orphan rule.

So now i want to implement '+' operator for every struct that implements MyTrait without using std::ops::Add trait.

Traits are how operator overloading is implemented in Rust (as well as most other "lifecycle" / "compiler" hooks). So you're basically asking how to implement the + operator without implementing the + operator.

The answer is that you can't.

So you can either:

  • use a declarative macro to implement both your trait and Add
  • not use the + operator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM