If with a short statement

Like for, the if statement can start with a short statement to execute before the condition.

Variables declared by the statement are only in scope until the end of the if.

(Try using v in the last return statement.)

if-with-a-short-statement.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. }
  10. return lim
  11. }
  12. func main() {
  13. fmt.Println(
  14. pow(3, 2, 10),
  15. pow(3, 3, 20),
  16. )
  17. }