Golang. Funny basic example of `if/else`


There is a resource for newcomers to the Go language – “A Tour of Go“. There’s a funny example in the beginning by number 7..

If and else

Variables declared inside an if short statement are also available inside any of the else blocks.

(Both calls to pow return their results before the call to fmt.Println in main begins.)

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\n", v, lim)
	}
	// can't use v here, though
	return lim
}

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

This gives output:
27 >= 20
9 20

but by the logic (at first glance) it seems that it should give this one:
9
27 >= 20
20

Why it so? There is a hint on side: (Both calls to pow return their results before the call to fmt.Println in main begins.).. but it’s not easy to get it…

The secret is… that fmt.Println doesn’t print until both other pow functions are evaluated, and the pow function itself can also print while evaluating. So the order of program execution is:

1. pow(3, 2, 10)
2. pow(3, 3, 20)
3. fmt.Println(…)

The first call returns 9 (printing nothing)
The second call prints 27 >= 20 and then returns 20
The final call prints 9 20

Voila!


This entry was posted in Go (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.