Marcos
Marcos

Reputation: 365

Golang: arithmetic operators on structs

Is there a way to define artihmetic ooerators between structs? Im using a decimal package to work with fixed decimal positions and avoid floats rounding erre ta. Ir defines operations cAlling functions like mul, add, sub, etc. Id like to use that structure like i do with floats: 6 / 2, not decimal.newfromfloat(6).div(newfromfloat(2)) I was hoping to find something interface to implement which alouds me to do that kind of operations, or maybe some kind of getter setter to work with the underlying valúes... Any ideas?

Upvotes: 3

Views: 5983

Answers (1)

Ainar-G
Ainar-G

Reputation: 36249

No, you can't overload operators in Go. There is a FAQ entry about it:

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.

https://golang.org/doc/faq#overloading

If you need a working solution, look at how package math/big deals with arithmetic sans operator overloading.

Upvotes: 4

Related Questions