I am new to Go and very confused with one of the sample codes in the tutorial. Here is the code and its output:
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)
}
return lim
}
func main() {
fmt.Println(pow(3, 3, 10), pow(4, 3, 20))
}
When I run it, the output of this code is:
27 >= 10
64 >= 20
10 20
Which is quite strange to me! I expect this output:
27 >= 10
10
64 >= 20
20
Can someone please help me to understand what is going on with Println in this code?
In Go, as in the vast majority of modern programming languages, the arguments of a function call are evaluated before the function call itself. Consider the following function:
func add(i, j int) int {
return i + j
}
And let's call it like this:
func a() int {
return 2
}
func b() int {
return 3
}
// ... somewhere in main()
add(a(), b())
You would expect that, by the time the code of add
runs, the values of i
and j
are known, right? The call would then return 5
as expected. To enable this, the Go compiler arranges for the arguments of add
- namely a()
and b()
to be run before add
itself runs.
The same happens in your code sample with Println
and pow
. The arguments to Println
need to be evaluated before its body is run, and evaluating pow
causes other things to be printed.