简体   繁体   English

如何在不使用 ops::Add 特征的情况下重载运算符?

[英]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我想为每个实现 MyTrait 的结构实现“+”运算符,所以我尝试了这个

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 .但我得到错误: 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.所以现在我想在不使用std::ops::Add trait 的情况下为每个实现MyTrait的结构实现 '+' 运算符。

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).原因是 Rust 具有禁止板条箱(您)为类型实现特征的孤儿规则,除非其中至少一个(特征或类型)由该板条箱(您)定义。

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).您正在尝试为所有类型T实现std::op::Add (在另一个板条箱std中定义的特征),其中一些类型不一定由您定义(因为任何板条箱都可以定义新类型)。 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.所以现在我想在不使用std::ops::Add trait 的情况下为每个实现MyTrait的结构实现 '+' 运算符。

Traits are how operator overloading is implemented in Rust (as well as most other "lifecycle" / "compiler" hooks).特征是在 Rust (以及大多数其他“生命周期”/“编译器”挂钩)中实现运算符重载的方式。 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使用声明性宏来实现您trait 和Add
  • not use the + operator不使用+运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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