Golang: if then else

By Xah Lee. Date: . Last updated: .

If

package main

import "fmt"

func ff(x int) string {
        if x < 0 {
                return "no"
        }
        return "yes"
}

func main() {
        fmt.Println(ff(-1), ff(2))
}

// no yes

Note, there's no parenthesis after the “if”.

If else

package main

import "fmt"

func ff(x int) string {

        if x < 0 {
                return "no"
        } else {
                return "yes"
        }

}

func main() {
        fmt.Println(ff(-1), ff(2))
}

// no yes

else if

package main

import "fmt"

func ff(x int) int {

        if x < 0 {
                return -1
        } else if x > 0 {
                return 1
        } else {
                return 0
        }

}

func main() {
        fmt.Println(ff(-2), ff(2), ff(0))
}

// -1 1 0

If with a short statement

The if statement can start with a short statement to execute before the condition.

Variables declared by the statement are in scope of the if block and all the else blocks.

package main

import "fmt"

func ff(x int) string {

        // if statement can start with a short statement, e.g. var declaration
        if i := -2; x < i {
                return "no"
        }
        return "yes"
}

func main() {
        fmt.Println(ff(-1), ff(2))
}

// yes yes

ternary if, if expression

There's no “if expression”, such as JavaScript's ( test ? expr1 : expr2 )

Reference

The Go Programming Language Specification - The Go Programming Language#If_statements

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Package, Import
  3. Function
  4. Variable
  5. Constant
  6. If Then Else
  7. switch/case
  8. Loop
  9. Basic Types
  10. Array
  11. Slice
  12. map
  13. read file
  14. Write to File
  15. Go Spec