有没有办法在结构之间定义算术运算符? 我正在使用小数包来处理固定的小数位并避免四舍五入的 float 错误。 Ir 定义操作调用函数,如 mul、add、sub 等。 我喜欢像使用 float 一样使用该结构:6/2,而不是 decimal.newfromfloat(6).div(newfromfloat(2)) 我希望找到一些接口(interface)来实现,让我大声做那种操作,或者可能是某种 getter setter 来处理底层的值......有什么想法吗?
最佳答案
不,您不能在 Go 中重载运算符。有一个关于它的 FAQ 条目:
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
如果您需要一个可行的解决方案,请查看如何打包 math/big
处理算术无运算符重载。
关于math - 戈朗 : arithmetic operators on structs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39590974/