dtyqeoc70733 2012-11-22 13:46
浏览 117
已采纳

为什么Go中的big int api如此奇怪?

I'm trying to understand the design decisions behind the big int api.

For example to add two big ints you have to:

a := big.NewInt(10)
b := big.NewInt(20)
c := big.NewInt(0)
d := c.Add(a,b)

where d is the same as c at the end. The initial zero does not matter a bit.

Why not just:

a := big.NewInt(10)
b := big.NewInt(20)
c := big.Add(a,b)

Or better yet:

a := big.NewInt(10)
b := big.NewInt(20)
c := a.Add(b)

Is there any reason they chose to do it this way? I find it little confusing and have to look it up whenever I use it.

  • 写回答

2条回答 默认 最新

  • duanhao5038 2012-11-22 13:51
    关注

    Add is a method changing the receiver.

    So just do

    c := big.NewInt(0).Add(a,b)
    

    or

    var c big.Int
    c.Add(a,b) 
    

    The fact that Add returns the receiver is useful for function chaining but you don't need to use the returned value.

    Now suppose a moment that we wouldn't have a bigInt as receiver (c := big.Add(a,b)) or that the receiver wouldn't be modified (c := a.Add(b)). In both cases a big Int would have to be allocated just for the operation and returned (as a pointer). This would be wasteful in case you yet have a big Int allocated and ready. The integer that is computed isn't just a simple one or two words struct, it can be big. So it's better to allow the use of a predefined var, especially as you often would use your big integer in the middle of a computation loop.

    c := big.Add(a,b) // wasteful because doesn't allow the use of a preexisting big int
    
    c := a.Add(b) // either modifies a (which would force you to copy it each time if you want to keep it) or is wasteful like the last one
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作