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 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?