Golang tutorial - 3 Control Flow (Selection)
Tags: go, beginners, tutorial
Published: 2020-05-18 09:54:12

Selection is a mechanism to execute certain code based on specified conditions. There are four types of condition selection in Go :
* selection using `if..` 
* selection using `if...else` 
* selection using `if...else if...else` 
* selection using `switch` `case`

##Operators
Before learning selection in Go, let’s take a look at operators that can be used in condition selection :
* ( `||` ) defines OR logical operator: If there is one or two conditions equals to true, then the result is true. If all of the conditions are false, the result is false.

	|Condition        | Condition            | Result  |
	| ----------------|:--------------------:| -------:|
	|true		  | true 		 | true    |
	|true		  | false		 | true    |
	|false		  | true		 | true    |
	|false		  | false		 | false   |

* ( `&&` ) defines AND logical operator: The result equals true if two conditions are true, if one of the conditions is false, the result is false.

	|Condition        | Condition           | Result |
	| ----------------- |:--------------------:| -------:|
	|true		| true 		   | true   |
	|true		| false		   | false  |
	|false		| true		   | false  |
	|false		| false		   | false  |

* ( `>` ) defines greater than operator
* ( `>=` ) defines greater or equal operator
* ( `<` ) defines less than operator
* ( `<=` ) defines less or equal operator
* ( `==` ) defines equal operator
* ( `!=` ) defines not equal operator
* ( `!` ) defines the negation of the statement 

	|Condition        | Result | 
	| ----------------- |:--------:| 
	|!true		| false 	|	   
	|!false		| true	|	   

##Selection using if... statement
The anatomy of the if... statement in Go is like this :
`if condition { ... }`
The code inside the if condition will be executed if the conditions are true.
Here is an example of using an if condition to check whether the number is odd or even.
```go
package main

import (
	"fmt"
)

func main() {
	a := 42
	if a%2 == 0 { //check if value of variable a is an even number
		fmt.Println("This is even number")
	}
}
```
The output from that code is :
```bash
This is even number
```
##Selection using if...else statement
The anatomy of the if...else statement is like this :
`if condition {
	//code
} else {
	//code
}`
The code inside the if condition will be executed if the conditions are true, otherwise, will be executed inside the else statement.
From the example above, let's add the `else` statement and change the value in the `a` variable.
```go
package main

import (
	"fmt"
)

func main() {
	a := 45
	if a%2 == 0 { //check if value of variable a is an even number
		fmt.Println("This is even number")
	} else {
		fmt.Println("This is odd number")
	}
}
```
The output from that code is :
```bash
This is odd number
```
##Selection using if...else if...else statement
The anatomy of if...else if...else statement is like this :
`if condition {
	//code
} else if condition {
	//code
} else {
	//code
}`
The code inside the if statement will be executed if the conditions are true. Otherwise, the code will be executed inside the else if conditions. If there are no true conditions, the code finally will be executed inside the else statement.
An example of using that statement is like this, the code will check the value from the grade variable and print out the grade result in alphabet character.
```go
package main

import (
	"fmt"
)

func main() {
	grade := 79
	if grade < 50 {
		fmt.Println("D")
	} else if grade >= 50 && grade < 70 {
		fmt.Println("C")
	} else if grade >= 70 && grade < 80 {
		fmt.Println("B")
	} else if grade >= 80 && grade <= 100 {
		fmt.Println("A")
	} else {
		fmt.Println("undefined")
	}
}
```
The output from that code is :
```bash
B
```
##Selection using switch case statement
The anatomy of the switch case statement is like this :
`switch expression
case condition:
	//code
case condition:
	//code
default:
	//code
`
The code will be executed based on the case that matches with the defined expression beside the `switch` keyword. If there is no case it matches. The code inside the `default` keyword will be executed. 
The example of using a `switch` case statement can be seen in this code, this code will check the value from the user variable and print a welcome message based on the user's variable value.
```go
package main

import (
	"fmt"
)

func main() {
	user := "admin"

	switch user {
	case "user":
		fmt.Println("Welcome user !")
	case "manager":
		fmt.Println("Welcome manager!")
	case "admin":
		fmt.Println("Welcome admin!")
	default:
		fmt.Println("Who are you?")
	}
}
```
The output from that code is :
```bash
Welcome admin!
```
There is a `fallthrough` keyword in the switch case selection to execute another code under the matched case. Here is an example
```go
package main

import (
	"fmt"
)

func main() {
	user := "user"

	switch user {
	case "user":
		fmt.Println("Welcome user !")
		fallthrough
	case "manager":
		fmt.Println("Welcome manager!") //this code executed because of fallthrough keyword
	case "admin":
		fmt.Println("Welcome admin!")
	default:
		fmt.Println("Who are you?")
	}
}
```
The output from that code is :
```bash
Welcome user !
Welcome manager!
```
##Notes
In any condition selection using Go. We can apply expression as well.
The example is like this :
```go
package main

import (
	"fmt"
)

func main() {
	if x := 42; x%2 == 0 { //assign expression inside if statement
		fmt.Println("even")
	} else {
		fmt.Println("odd")
	}
}
```
The output from that code is :
```bash
even
```
This is the example using an expression inside switch case selection :
```go
package main

import (
	"fmt"
)

func main() {
	switch user := "manager"; user {
	case "user":
		fmt.Println("Hello user!")
	case "admin":
		fmt.Println("Hello admin!")
	case "manager":
		fmt.Println("Hello manager!")
	default:
		fmt.Println("who are you?")
	}
}
```
Output :
```bash
Hello manager!
```
The complex condition checking can be stored inside the variable to make the code more clean and readable. This is an example of using a variable to store complex condition checking.

```go
package main

import (
	"fmt"
)

func main() {
	username := "cooluser"
	password := "secrets"

	// condition description:
	// username is not empty and has length of minimum 6 characters
	// password is not empty and has length of minimum 6 characters
	isValid := username != "" && len(username) >= 6 && password != "" && len(password) >= 6

	if isValid {
		fmt.Println("registered!")
	} else {
		fmt.Println("validation failed")
	}
}

```

Output:

```bash
registered!
```

##Sources
* Learn more about if statement [here](https://go.dev/ref/spec#If_statements)
* Learn more about switch statement [here](https://go.dev/ref/spec#Switch_statements)

I hope this article helps to learn the Go programming language. If you have any thoughts or feedback, you can write it in the discussion section below.