Comp Lang: Necessity of Operator Overload
Python Example of Operator Overload
class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): # Overload the + operator to add corresponding components return Vector(self.x + other.x, self.y + other.y) def __str__(self): # For readable output when printing the vector return f"Vector({self.x}, {self.y})" # Example usage v1 = Vector(1, 2) v2 = Vector(3, 4) v3 = v1 + v2 # This calls the __add__ method print(v3)
golang doesn't have operator overloading.
go frequently asked questions says:
Why does Go not support overloading of methods and operators?
Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.
Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it.
this is a problem.
actually, operator overloading may not be necessary, but defining new operator is extremely convenient when doing math.
for example, when you are doing linear algebra.
say, M and N are matrixes, v is a vector. you want to be able to write:
M △ N ▲ V
matrixVectorTimes(matrixTimes(M,N), v)
if we reduce the function name, it has the function form:
f(g(a,b),c)
wouldn't that solve the problem? No, because, the question is really about, why is operator such as + - * / = needed in the first place? why can't they all be function form? The answer is, without operators, expressions becomes extremely cumbersome and unreadable.
things gets real complex when you have complex numbers in play.