DEV Community

Cover image for if else golang
tcs224
tcs224

Posted on

if else golang

If-else lets you branch code. A branch is a block of code (1 or more lines) that is executed on certain conditions. This is called an if statement.

Most programming languages support branching (C, C++, Java, Python, Perl etc). In Golang these branching options exist:

  • if
  • if..else
  • if..else if....else
  • switch..case

Before learning about if statements, make sure you can run Go programs.

If..else example

The program below shows an example of if-else branching in Go. The variable legs is set. Which code block is executed depends on the value.

package main

import (
    "fmt"
)

func main() {
        legs := 4
    if legs == 4 {
        fmt.Println("Cat")
    } else {
        fmt.Println("Spider")
    }
}

If example

Without an else clause, it just executed the branch if the condition is true. In this example its true if x is greater than 1.

package main

import (
    "fmt"
)

func main() {
    var x = 2
    if x > 1 {
        fmt.Println("x greater than 1")
    }
}

If elseif else

In this example the use of if..elseif..else is used. You can check multiple conditions at once instead of writing the if-statement over and over.

package main

import (
    "fmt"
)

func main() {
    var x = 2
    if x == 1 {
        fmt.Println("x is 1")
    } else if x == 2 {
        fmt.Println("x is 2")
    } else if x == 3 {
        fmt.Println("x is 3")
    } else {
        fmt.Println("x is something else")
    }
}

Related links:

Top comments (0)