Golang If-Else, Switch Statement – Control Flow

Share this blog with others!

In this blog, we will learn about Golang If-else and Switch Statements.

Let’s see what we will learn in Golang if-else and switch statementsControl Flow:

  • Golang If-else Statement (Control Flow)
    • Operators
    • If-else and if-else-if statement
  • Golang Switch Statement
    • Simple cases
    • Cases with multiple tests
    • Fall Through in Golang (Spoiler There’s no Fall Through in Golang )
    • Type Switches in Golang

Before learning Golang If-else and Switch Statements, make sure to learn the basics of Go:

Golang If Statement Assignment

if <Condition> { // Statement }else{ // Statement }

Golang Ifelse Statement Syntax Control Flow:

	if true {
		fmt.Println("Hello World!")
	}

Output:

Hello World!

	if false {
		fmt.Println("Hello World!")
	}

No output as the if block doesn’t execute.

Golang If-Else vs C If-Else

No Newline block

if true
{
	fmt.Println("Hello World!")
}

OR

if true
{
	fmt.Println("Hello World!")
}
else
{
	fmt.Println("Else Block")
}

Syntax Error : – syntax error: unexpected newline, expecting { after if clause

The Correct Syntax for Golang if-else Statement is:

if true {
	fmt.Println("Hello World!")
}

OR

if true {
	fmt.Println("Hello World!")
} else {
	fmt.Println("Else Block")
}

Output- Hello World!

Golang If-else Always Maintains Block

In other languages like C, C++, or Java, it is not necessary to define a block using ‘{‘ for a single statement. like:

C++ If-Else example:

if(true)
    std::cout<<"Hello World"<<std::endl;

But in Go, it is mandatory to put braces for a single line of statement too.

Golang If-else Example:

	if true
		fmt.Println("Hello World!")

Error: – syntax error: unexpected newline, expecting { after if clause

Golang If-else Statement Initializer Syntax

if <Initializer> ; <Condition> { // Statement }

package main

import (
	"fmt"
)

func main() {
	csMarks := map[string]int{
		"Divyanshu Shekhar": 99,
		"Arpit Sahu":        98,
		"Shubham Ranjan":    90,
		"Sourabh Kumar":     95,
	}

	if ds, ok := csMarks["Divyanshu Shekhar"]; ok {
		fmt.Println(ds)
	}
}

Output:- 99


if ds, ok := csMarks["XYZ"]; ok {
	fmt.Println(ds)
} else {
	fmt.Println("Key Not Present in the Map")
}

Output:

Key Not Present in the Map

Operations in Golang Control Flow

	n := 5
	x := 5
	if x < n {
		fmt.Println(x, "<", n)
	}
	if x > n {
		fmt.Println(x, "<", n)
	}
	if x == n {
		fmt.Println(x, "==", n)
	}

Output:

5 == 5

Golang If-Else Logical Operations

Go Logical AND (&&) and Logical OR (||) can be used to get bool results for the Golang if-else condition test.

Logical AND (&&)

ABA && B
000
010
100
111
Logical AND
	marks := 85
	if marks >= 90 {
		fmt.Println("A+")
	}
	if marks < 90 && marks >= 80 {
		fmt.Println("B+")
	}
	if marks < 80 && marks >= 70 {
		fmt.Println("C+")
	}

Output – B+

Logical OR ( || )

ABA || B
000
011
101
111
Logical OR
	marks := 105
	if marks < 0 || marks > 100 {
		fmt.Println("Invalid marks")
	}

Output:- Invalid marks

Not Operator (!)

fmt.Println(!true)
fmt.Println(!false)

Output:

false

true

Golang If-Else Short circuit evaluation

Logical OR operator needs only one test condition to be true and it executes even without checking the second or third statement.

package main

import (
	"fmt"
)

func check() bool {
	fmt.Println("Check Function Executed")
	return true
}

func main() {

	marks := 90
	if marks < 100 || check() {
		fmt.Println("Logical OR Short circuit")
	}

}

Output:

Logical OR Short circuit

But, when we make the first condition false. i.e marks < 100 == false

Let’s see.

	marks := 105
	if marks < 100 || check() {
		fmt.Println("Logical OR Short circuit")
	}

Output:

Check Function Executed
Logical OR Short circuit

And, in Logical AND operator needs only one test condition to be false and it doesn’t test the other statement and executes the block.

	marks := 105
	if marks < 100 && check() {
		fmt.Println("Logical AND Short circuit")
	} else {
		fmt.Println("Else Block")
	}

Output:

Else Block

Making the first condition true. i.e marks < 100 == true

	marks := 90
	if marks < 100 && check() {
		fmt.Println("Logical AND Short circuit")
	} else {
		fmt.Println("Else Block")
	}

Output:

Check Function Executed
Logical AND Short circuit

Golang If-Else-if ladder

Looking at the previous example:

	marks := 85
	if marks >= 90 {
		fmt.Println("A+")
	}
	if marks < 90 && marks >= 80 {
		fmt.Println("B+")
	}
	if marks < 80 && marks >= 70 {
		fmt.Println("C+")
	}

There are many if-statements in this Go Program and the Go Compiler has to look at every if-statement.

In this example, if the mark is greater than or equal to 90 the output will be A+, and it is not possible that the mark will become less than 90 when we check it next time but the Go compiler will check every if-statement.

So, we need an if-else-if ladder in Golang in order to check the condition and if any condition passes it will not check other conditions.

Example:

	marks := 85
	if marks >= 90 {
		fmt.Println("A+")
	} else if marks < 90 && marks >= 80 {
		fmt.Println("B+")
	} else if marks < 80 && marks >= 70 {
		fmt.Println("C+")
	} else {
		fmt.Println("D")
	}

Golang Nested If-Else

If-Else Statement inside an If-Else is called Nested If-Else.

package main

import (
	"fmt"
)

func check() bool {
	fmt.Println("Check Function Executed")
	return true
}

func main() {
	a := 5
	b := 8
	c := 2
	if a > b {
		if a > c {
			fmt.Println("a is greatest")
		} else {
			fmt.Println("c is greatest")
		}
	} else {
		if b > c {
			fmt.Println("b is greatest")
		} else {
			fmt.Println("c is greatest")
		}
	}

}

Output:

b is greatest

Next we’ll learn about Golang Switch Statement.

Golang Switch

switch <Tag> { //Cases }

func main() {
	n := 1
	switch n {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("Two")
	default:
		fmt.Println("Invalid")

	}

}

Output:

one

Golang Switch Syntax

switch <Initializer> ; <Tag> { //Cases }

Code:

	switch n := 5 - 4; n {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("Two")
	default:
		fmt.Println("Invalid")

	}

Output: one

Golang Tagless Switch

We can also make Golang switch cases tagless.

Example:

	a := 5
	b := 8
	switch {
	case a > b:
		fmt.Println("a is greater than b")
	case a < b:
		fmt.Println("b is greater than a")
	default:
		fmt.Println("a is equal to b")

	}

Output:

b is greater than a

Multiple Tests in single Switch Case

Let’s make a program to print whether a number between one – ten is an odd or even number using multiple tests in Golang Switch-case statements.

Code:

	// Number between 1-10 (endpoints included)
	n := 5
	switch n {
	case 1, 3, 5, 7, 9:
		fmt.Println("Odd Number")
	case 2, 4, 6, 8, 10:
		fmt.Println("Even Number")
	default:
		fmt.Println("Invalid | Out of Range")

	}
when n=5, Odd
when n=8, Even
when n=12, Invalid | Out of Range

Golang Switch Fallthrough

There is no Fall through in Golang Switch Case.

	n := 1
	switch n {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("Two")
	default:
		fmt.Println("Invalid")

	}

As in Other languages, we expect a fallthrough as we’re missing the break statements in the switch case statement. Expected Output- one \n two \n Invalid. Real Output – one.

This program also gives the same output as the first one. so there is no fall-through in Golang Switch Case. The Break keyword is automatically handled behind the scenes and thus we don’t see any difference.

If you want to make use of fall through in Golang Switch Case, there is indeed a fallthrough keyword in Golang that helps us to implement Fall Through feature in Golang.

Golang Fallthrough Keyword

	n := 1
	switch n {
	case 1:
		fmt.Println("one")
		fallthrough
	case 2:
		fmt.Println("Two")
	default:
		fmt.Println("Invalid")

	}

Fall Through Output:

one
Two

Golang Type Switch

	var n interface{} = 1
	switch n.(type) {
	case int:
		fmt.Println("int")
	case float64:
		fmt.Println("float")
	case string:
		fmt.Println("String")

	}

Output:

int

Golang interface{} type can take any value type i.e int, float, string, bool, etc.

n.(type) extracts the type of the variable n and then matches the cases in a switch statement.

Also, read Why Golang is called the future of Server-side language?

Learn more about Golang If-Else and Switch Statement from the official Documentation.

0 0 votes
Article Rating

Share this blog with others!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top