I know it is possible by using traits to implement operator overloading in Rust. In C++ is also possible to have multiple operator overloading for the same operator and the same struct
, and switch on/off which operator to use.
Is it possible to do the same as the following C++ code in Rust? Possibly in the same source file?
struct S
{
int value;
};
namespace first
{
S operator+(S lhs, S rhs)
{
return S{ lhs.value + rhs.value };
}
}
namespace second
{
S operator+(S lhs, S rhs)
{
return S{ lhs.value * rhs.value };
}
}
int main()
{
S s1{5};
S s2{10};
{
using namespace first;
S s3 = s1 + s2;
std::cout << s3.value << std::endl;
}
{
using namespace second;
S s3 = s1 + s2;
std::cout << s3.value << std::endl;
}
}
using namespace
, and always place operator overloads in the namespace of one of their arguments so they can be found by ADL. – Binominal