Order of evaluation:
At package level, initialization dependencies determine the evaluation
order of individual initialization expressions in variable
declarations. Otherwise, when evaluating the operands of an
expression, assignment, or return statement, all function calls,
method calls, and communication operations are evaluated in lexical
left-to-right order.
For example, in the (function-local) assignment
y[f()], ok = g(h(), i()+x[j()], <-c), k()
the function calls and communication happen in the order f(), h(),
i(), j(), <-c, g(), and k(). However, the order of those events
compared to the evaluation and indexing of x and the evaluation of y
is not specified.
a := 1
f := func() int { a++; return a }
x := []int{a, f()}
m := map[int]int{a: 1, a: 2}
n := map[int]int{a: f()}
At package level, initialization dependencies override the
left-to-right rule for individual initialization expressions, but not
for operands within each expression:
var a, b, c = f() + v(), g(), sqr(u()) + v()
func f() int { return c }
func g() int { return a }
func sqr(x int) int { return x*x }
// functions u and v are independent of all other variables and functions
The function calls happen in the order u(), sqr(), v(), f(), v(), and
g().
Floating-point operations within a single expression are evaluated
according to the associativity of the operators. Explicit parentheses
affect the evaluation by overriding the default associativity. In the
expression x + (y + z) the addition y + z is performed before adding
x.
If you need:
9
27 >= 20
20
First call pow(3, 2, 10)
and Print
the result, like this working sample code:
package main
import "fmt"
import "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, 2, 10))
fmt.Println()
fmt.Println(pow(3, 3, 20))
}
output:
9
27 >= 20
20
See the order of function calls in this working sample code:
package main
import "fmt"
func pow(n float64) float64 {
fmt.Println("order:", n)
return n
}
func main() {
fmt.Println(pow(1), pow(2), pow(3))
}
output:
order: 1
order: 2
order: 3
1 2 3
And:
package main
import "fmt"
func pow(n int) int {
fmt.Println("order:", n)
return n
}
func main() {
a, b, c := pow(1), pow(2), pow(3)
fmt.Println("Order 4")
fmt.Println(a, b, c)
}
output:
order: 1
order: 2
order: 3
Order 4
1 2 3
package main
import "fmt"
func pow(n int) int {
fmt.Println("order:", n)
return n
}
func main() {
a := pow(1)
b := pow(2)
c := pow(3)
fmt.Println("Order 4")
fmt.Println(a, b, c)
}
output:
order: 1
order: 2
order: 3
Order 4
1 2 3