Condition Construct in GOLang

Japneet Singh Chawla
2 min readMar 23, 2020

Conditional programming is a very important construct available in all the programming languages.

Go provides 2 conditional programming constructs

  1. If else
  2. Switch

If Else

This is a very basic construct and is similar to most of the other languages.

If else can be written in the following way:

package mainimport "fmt"func main() {	i := 10
if i > 10 {
fmt.Println("Greater than 10")
} else {
fmt.Println("Less than 10")
}
}

We can also create an IF Else ladder in Golang

package mainimport "fmt"func main() {	i := 7
if i > 10 {
fmt.Println("Greater than 10")
} else if i > 5 {
fmt.Println("Greater than 5")
} else {
fmt.Println("Less than 5")
}
}

Switch Statement

Another alternative to IF Else is a Switch statement which is quite useful in Golang.

Following is a very basic example of a switch statement

package mainimport "fmt"func main() {
j := 2
switch j {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
}

We can also use logical statements and more than one statement in GO.

Following code shows using logical statements in Switch

package mainimport "fmt"func main() {
j := 2
switch {
case j < 5:
fmt.Println("one")
case j > 5:
fmt.Println("two")
case j == 5:
fmt.Println("three")
}
}

Following shows using multiple values in switch and default

package mainimport "fmt"func main() {	j := 5
switch j {
case 1, 2:
fmt.Println("one,two")
case 4:
fmt.Println("four")
default:
fmt.Println("default")
}
}

This shows default and switch constructs and we don’t need to use a break after all the conditions.

I hope the content helps you.

You can learn about the arrays in my previous blog.

Happy Learning.

--

--