dongyuan2652 2015-09-16 21:07
浏览 37
已采纳

此Go打印语句的顺序是什么?

I'm taking 'A Tour of GO' tutorial about Golang and this code:

package main

import (
    "fmt"
    "math"
)

func pow(x, n, lim float64) float64 {
    if v := math.Pow(x, n); v < lim {
        return v
    } else {
        fmt.Printf("%g >= %g
", v, lim)
    }
    // can't use v here, though
    return lim
}

func main() {
    fmt.Println(
        pow(3, 2, 10),
        pow(3, 3, 20),
    )
}

would print "27 >= 20 9 20".

I'm rather confused why it's not "9 27 >= 20 20"

Shouldn't the first call to pow(3,2,10) return 9, print it, then call pow(3,3,20) and print the rest?

  • 写回答

2条回答 默认 最新

  • douqihou7537 2015-09-16 21:31
    关注

    This is actually somewhat subtle and had me confused for a second. The "secret" is that a function must evaluate all its arguments before it's called. So it calls the function twice to get 9 and 20, but one of those evaluations happens to call Println.

    It's fairly straightforward why the language evaluates its arguments before calling a function (that sort of partial application is tricky when side effects are involved, and is mostly reserved for functional languages), but hiding functions with side effects such as printing inside a function evaluation should probably be discouraged just for the purposes of clarity.

    The code is perhaps more straightforwardly:

    func main() {
        arg1,arg2 := pow(3,2,10),pow(3,3,20)
        fmt.Println(arg1, arg2)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换