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.)

if-and-else.go

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func pow(x, n, lim float64) float64 {
  7. if v := math.Pow(x, n); v < lim {
  8. return v
  9. } else {
  10. fmt.Printf("%g >= %g\n", v, lim)
  11. }
  12. // can't use v here, though
  13. return lim
  14. }
  15. func main() {
  16. fmt.Println(
  17. pow(3, 2, 10),
  18. pow(3, 3, 20),
  19. )
  20. }