math - 戈朗 : arithmetic operators on structs

标签 math go structure

有没有办法在结构之间定义算术运算符? 我正在使用小数包来处理固定的小数位并避免四舍五入的 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/

相关文章:

java - 使用类型继承的数字组层次结构

java - 在java中测试公式中的括号是否匹配,我的算法是否正确?

java - 如何计算以字符串形式给出的数学表达式?

python - 举例说明为什么四元数可以防止万向节锁定

go - 同时读取和写入数组是否安全 Go

go - 从 go 获取 Windows 全名的最佳方法是什么?

c - 双向链表问题?

c - 是否有必要使用数据结构对齐

go - 将 RSA PrivateKey PEM 写入 golang 文件

使用结构在另一个双向链表中创建一个双向链表