Condition Construct in GOLang


Condition Construct in GOLang

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 main

import "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 main

import "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 main

import "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 main

import "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 main

import "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.

Comments

  1. You have provided a nice article, Thank you very much for this one. And I hope this will be useful for many people. And I am waiting for your next post keep on updating these kinds of knowledgeable things.
    Salesforce Training Australia  

    ReplyDelete

Post a Comment

Popular posts from this blog

Word Vectorization

Spidering the web with Python

Machine Learning -Solution or Problem