Control Statements - Control Your Go
Tags: conditionalstatements, loopingstatements, controlstatements, go
Published: 2023-04-05 05:13:28

**"Journey With Go - A Blog Series"** about the basics of Go `Go Basic`, advanced concepts in Go `Go Beyond Basics`, testing with go `Godog as Test Framework` and many more.

This is the second installment of the series. You are here, which means you have already read the first blog of the series. If you haven't read the first blog, please read it first. It is available [here](https://dev.to/jankaritech/go-basics-the-starting-point-5agf "here"). In this blog, we will learn about the `Control Flow Statements in Go`. **So, let's get started.**

## **Control Flow Statements**

These statements are used to control the flow of the program. In other words, they control the execution of the program. There are two types of control flow statements in Go.

1. Branching Statements
2. Looping Statements

### **A. Branching Statements**

Branching statements divide the program into different branches on the basis of a given condition. Some blocks of code might execute and some might not. In Go, we have `if-else` and `switch` to control the flow of the program.

#### 1. if-else

If the condition is true, it executes the code inside the `if` block otherwise (i.e., the condition is false), it executes the code inside the `else` block. There are different forms of `if-else` pairs such as, `if`, `if-else`, `nested if-else`, and `else-if ladder`.

##### _a. if_

This can be used if you want to execute the code only if the condition is true. The syntax of `if` is as follows.

```go
if condition {
    // code to execute if the condition is true
}
```

![If Flowchart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjzq1t98a832y790yrcz.png "If Flowchart")

**Example:**

![If Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uoxg1x3q0u069hpdnz5s.png "If Example")

**Output:**

```go
You are eligible to receive a Citizenship
```

##### _b. if-else_

When you want to execute codes either for true or false cases then `if-else` can be used. `if-else` executes the code inside the `if` block if the condition is true otherwise, it executes the code inside the `else` block. The syntax of `if-else` is as follows.

```go
if condition {
    // code to execute if the condition is true
} else {
    // code to execute if the condition is false
}
```

![If-Else Flowchart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1drbymzlmk9ydzglsuav.png "If-Else Flowchart")

**Example:**

![If-Else Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pe2s83o4cqghhj2h9yqy.png "If-Else Example")

**Output:**

```go
You are eligible to vote.
```

##### _c. nested if-else_

If the if-else statement is inside another if-else statement, it is called a nested if-else statement. We can use nested if-else statements to check other conditions if the previous condition is met. We have different variations of nested if-else statements. We will discuss only one of them.
The syntax of `nested if-else` is as follows.

```go
if condition {
    // code to execute if the condition is true
    if condition {
        // code to execute if the condition is true
    } else {
        // code to execute if the condition is false
    }
} else {
    if condition {
        // code to execute if the condition is true
    } else {
        // code to execute if the condition is false
    }
}
```

![Nested If-Else Flowchart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/95v1klskzrlqrc25j9gi.png "Nested If-Else Flowchart")

**Example:**

![Nested If-Else Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gt5a0iceccmatuniezzk.png "Nested If-Else Example")

**Output:**

```go
The greatest number is: 566
```

##### _d. else-if ladder_

The else-if ladder is a series of if-else statements. It is used when we have multiple conditions to check when the previous condition is not met. The syntax of `else-if ladder` is as follows.

```go
if condition {
    // code to execute if the condition is true
} else if condition {
    // code to execute if the condition is true
} else if condition {
    // code to execute if the condition is true
} else {
    // code to execute if none of the conditions are true
}
```

![Else-If Ladder Flowchart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4c02oj8abb882wfo1gz5.png "Else-If Ladder Flowchart")

**Example:**

![Else-If Ladder Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l2nn17jaxaq5oho4t0nk.png "Else-If Ladder Example")

**Output:**

```go
It is a Negative number
```

### 2. Switch

`switch` allows us to execute one block of code among several cases based on the value of a given expression. It can be used as an alternative to the `else-if ladder` statement when you have lots of conditions to be checked. If none of the cases match with the expression, the code inside the `default` block gets executed. The syntax of `switch` is as follows.

```go
switch expression {
    case value1:
        // code to execute if the expression matches with value1
    case value2:
        // code to execute if the expression matches with value2
    case value3:
        // code to execute if the expression matches with value3
    default:
        // code to execute if none of the cases match with the expression
}
```

![Switch Flowchart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06xy92pmov4e2x5bl0dr.png "Switch Flowchart")

**Example:**

![Switch Alternative](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rm3ndxsmvslggqwdvpy.png "Switch Alternative")

In the above example, we can see `else-if ladder` is used to check the day of the week. But there are lots of conditions to be checked. So, it is better to use the `switch` statement instead of the `else-if ladder` to achieve the same result.

![Switch Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lpfi1d249lylgovde41e.png "Switch Example")

**Output:**

```go
Tuesday
```

The `break` keyword is not required, as the `switch` statement automatically breaks the execution of the code as soon as the first case is matched.

But, we can use the `fallthrough` keyword to execute the code inside the next case. The syntax of `fallthrough` is as follows.

```go
switch expression {
    case value1:
        // code to execute if the expression matches with value1
        fallthrough
    case value2:
        // code to execute if the expression matches with value2
    case value3:
        // code to execute if the expression matches with value3
    default:
        // code to execute if none of the cases match with the expression
}
```

![Switch Fallthrough Flowchart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ds8q7szhb5bxb8hu647f.png "Switch Fallthrough Flowchart")

**Example:**

![Switch Fallthrough Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ocs8dlpirufa91d7odmq.png "Switch Fallthrough Example")

**Output:**

```go
It's Weekday
```

### **B. Looping Statements**

If we want to execute the block of codes repeatedly, we can use looping statements. The block of codes executes repeatedly until the condition is met. In Go, we have two ways to use a loop in the codes. They are `for` and `range`.

#### 1. for

The `for` loop allows a program to execute a block of code repeatedly if the condition is true. The syntax of `for` is as follows.

```go
for initialization; condition; increment/decrement {
  // code to execute if the condition is true
}
```

![For Loop Flowchart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3z1hgmxm9mg7f3jpwnka.png "For Loop Flowchart")

**Example:**

![For Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qe3w1uk96yxal8zeqmk1.png "For Example")

**Output:**

```go
1
2
3
4
5
```

We don't have a separate `while` loop in Go like other programming languages. We can use the `for` loop as a `while` loop as follows.

```go
for condition {
    // code to execute if the condition is true
}
```

**Example:**

![While Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kbmt41ky6z7602yj7epl.png "While Example")

**Output:**

```go
1
2
3
4
5
```

#### 2. range

`range` in the Go language is used to iterate over arrays, slices, maps, and strings. The `range` is used along with the `for` loop. The syntax of `range` is as follows.

```go
for index, value := range collection {
    // code to execute until every element of the collection is iterated
}
```

**Example:**

![Range Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g48vj2435tcv9z5onk2k.png "Range Example")

**Output:**

```go
Fruit at index 0 is Apple
Fruit at index 1 is Mango
Fruit at index 2 is Grape
Fruit at index 3 is Lichi
Fruit at index 4 is Strawberry
```
### **C. Other Statements**

Besides, if, switch, for, and range, the Go language also provides some other statements. They are `break`, `continue`, `defer`, and `panic`.
#### 1. Break Statement

The `break` statement terminates the loop or switch statement and transfers execution to the code immediately after the loop or switch. The keyword `break` is used.

**Example:**

![Break Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qc9q8seubsrnsq02cnlv.png "Break Example")

In the above example, the `break` statement terminates the `for` loop when the value of `i` is equal to 5. So, the output will be as follows.

**Output:**

```go
0
1
2
3
4
Done
```

#### 2. Continue Statement

The `continue` statement skips the current iteration of the loop and continues with the next iteration. The keyword `continue` is used.

**Example:**

![Continue Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2qqj33w1eyr5e49di9h9.png "Continue Example")

In the above example, the `continue` statement skips the current iteration of the loop when the value of `i` is equal to 5. So, the output will be as follows.

**Output:**

```go
0
1
2
3
4
6
7
8
9
Done
```

#### 3. Defer Statement

The `defer` statement invokes the function after the surrounding function returns. This delays the execution of the function. If there are multiple `defer` statements, they are executed in the last-in-first-out order. This statement might be useful for a cleanup task after the function has been executed. The syntax of `defer` is as follows.

```go
func functionToDoSomething() {
    defer deferFunction()
    // code to execute
}

func deferFunction(){
    // code to execute
}
```

**Example:**

![Defer Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3o9a8gidzthb0kqvbbm.png "Defer Example")

In the above example, the defer statements are pushed into the stack. And the last defer statement popped out first. The output will be as follows.

**Output:**

```go
Hello World, I am From Nepal.
```

#### 4. Panic Statement

The `panic` statement in Go is used to stop the normal flow of the program and start panicking. The `panic` statement is used to throw an exception. `panic()` is either raised by the Go runtime or can be raised by the user. The syntax of `panic` is as follows.

```go
panic("error message")
```

**Example:**

![Panic Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0xrx2upw9muaqokearej.png "Panic Example")

In the above example, the `panic` statement is raised by the user. The program terminates as panic is raised. The output will be as follows.

**Output:**

```go
panic: Something went wrong

goroutine 1 [running]:
main.main()
	/home/prarup/JankariTech/playground/go-code/panic.go:7 +0x27
exit status 2
```

#### 5. Recover Statement

The `recover` statement recovers from the `panic` state and resumes normal execution of the program if possible. The `recover` statement is used to catch the `panic` statement. The syntax of `recover` is as follows.

```go
recover()
```

**Example:**

![Recover Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ts8qpli4ci9tv2fan1n8.png "Recover Example")

In the above example, the `recover` statement is used to catch the `panic` statement. The output will be as follows.

**Output:**

```go
Something went wrong
```


## What we have learned so far

- Branching Statements
  - if-else
  - switch
- Looping Statements
  - for
  - range
- Break Statement
- Continue Statement
- Defer Statement
- Panic Statement
- Recover Statement

## Conclusion

In this blog, we have learned about the control flow in the Go language. We have learned about the branching statements and looping statements. We have also learned about the `break`, `continue`, `defer`, `panic`, and `recover` statements. In the next blog, we will learn about the functions, Arrays, Strings, and Structures in the Go language. *Keep learning and keep practicing*. **Stay tuned!!!**.

## References

- [Go Programming Language](https://go.dev/ "Go Programming Language")
- [Go by Example](https://gobyexample.com/ "Go by Example")
- [Go Documentation](https://go.dev/doc/ "Go Documentation")
- [Go Playground](https://play.golang.org/ "Go Playground")
- [Go Tour](https://tour.golang.org/welcome/1 "Go Tour")