donglian4464 2016-09-20 09:52
浏览 57
已采纳

Golang:结构上的算术运算符

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?

  • 写回答

1条回答 默认 最新

  • duanqianhuan3994 2016-09-20 10:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址