In this tutorial we will learn about conditional statements(If-Then-Else), Loops and Switches in Go.
This blog is part of the tutorial series – Learn Go, in which we will learn about Go language step by step.
Table of Contents
1.0 If-Then-Else
If-Then-Else statement allows us to conditionally execute our code.
It’s syntax is
if [condition] { // code - executed when the if condition evaluates to true } else if [condition] { // code - executed when the else if condition evaluates to true } else { // code - executed when none of above condition evaluates to true }
Note: The condition expression does NOT needs to be surrounded by a paranthesis (), but the braces {} are required around the code block of
if
1.1 If
Let’s start by looking a simple example of if
statement
if num%2==0 { fmt.Println("Even Number") }
Above code will print “Even Number
“, only if the condition num%2==0
evaluates to true
(where num
is some variable)
1.2 If-Else
Now let’s extend above example to an If-Else statement
if num%2==0 { fmt.Println("Even Number") } else { fmt.Println("Odd Number") }
In above example, the else
statement is executed all the if
statments above it evaluate to false
.
e.g if the value of num
is 2, then Even Number
will be printed by above code.
if the value of num
is 3, then Odd Number
will be printed by above code.
1.3 If-ElseIf
We can also write a series of if
statements one after the other.
As soon as the first if
condition evaluates to true
, its body is executed and rest all if
statements below it are skipped. e.g
if env == "uat" { fmt.Println("Apply UAT environment config") } else if env == "prod" { fmt.Println("Apply Production config") } else if env == "dev" { fmt.Println("Apply Dev config") } else { fmt.Println("Invalid Environment") }
We can write as many else if
statements as we may require.
1.4 If with a short statement
Sometimes we may want to execute some short statements, before the condition of if
statement is evaluated. e.g.
if remainder := num % 5; remainder == 0 {
fmt.Printf("%d is divisible by 5 ", num)
} else {
fmt.Printf("%d is not divisible by 5. Remainder = %d", num, remainder)
}
As you can see in above example, we declared and initialized a variable remainder
, before the condition is evaluated.
In above example, Short statement is remainder := num % 5
, and Condition expression is remainder == 0
Variables declared by the statement are only in scope until the end of the
if
.
So in above example, the variable remainder
can only be accessed from within the if
statement and not outside it.
2.0 Switch
Switch
statements are another ways of writing a sequence of if-else
statements. Each switch
statement consists of multiple case
statements. As soon as the first case
statement matches, it is executed and all case
statements below it are skipped.
Switch also has a default
case, which is executed if no other case
statement matches.
If you are coming from the
Java
world, this may seem a little different.In Java, all case statements below the matching case are also executed, unless you write a
break
statement to exit the switch.In Go, there is NO need to write a
break
statement to exit the switch
Let’s look at few examples of switch-case
2.1 Simplest Switch statement
Remember the if-elseif example that we wrote above. We will now re-write the same example as a switch-case
statement.
switch env { case "uat": fmt.Println("Apply UAT environment config") case "prod": fmt.Println("Apply Production config") case "dev": fmt.Println("Apply Dev config") default: fmt.Println("Invalid Environment") }
Let’s look at another good example of switch (which is taken from the Go Tour)
fmt.Print("When is Saturday? : ") today := time.Now().Weekday() switch time.Saturday { case today + 0: fmt.Println("Today.") case today + 1: fmt.Println("Tomorrow.") case today + 2: fmt.Println("In two days.") default: fmt.Println("Too far away.") }
2.2 Switch with a short statement
Just like we had a short statement at the start of an if
statement, we can do the same with a switch statement too.
switch env_ci := strings.ToLower(env); env_ci {
case "uat":
fmt.Println("Apply UAT environment config")
case "prod":
fmt.Println("Apply Production config")
case "dev":
fmt.Println("Apply Dev config")
default:
fmt.Println("Invalid Environment")
}
In above example, we first declare and initialize a variable env_ci
at start of switch statement -> env_ci := strings.ToLower(env)
Then after the semicolon (;
) we provide the expression for the switch -> env_ci
As with the if statement, the scope of any variable declared and initialized in the switch statement is only within the switch statement and not outside it.
2.3 Switch without any condition expression
We can also write a switch statement without any condition expression.
In this case it becomes exactly equivalent to an If/Then Else statement.
Look at following example below
func getGrade(marks int) string { var grade string switch { case marks >= 90: grade = "Passed : A+" case marks >= 75 && marks < 90: grade = "Passed : B+" case marks >= 60 && marks < 75: grade = "Passed : C+" case marks >= 40 && marks < 60: grade = "Passed : D+" default: grade = "Failed" } return grade; }
3.0 Loops
Loops are core features of any programming language. You need loops if you want some part of your code to execute again and again in iteration.
You might be aware of for
and while
loops in Java.
Go only provides one loop construct – the FOR
loop
3.1 For Loop
The basic syntax of For loop in Go is as below
for [init-statement] ; [condition-expression] ; [post-statement] { [body] }
For Loop consist of 4 parts
- init-statement
- Executed only ONCE, when the For loop starts execution
- You can declare and initialize some variable as part of this. e.g initializing a loop counter.
- condition-expression
- A boolean conditional expression.
- Condition expression is evaluated at start of every iteration of loop.
- Loop execution continues, till this condition evaluates to
true
.
- post-statement
- This is the statement of code that is executed at the end of any iteration of loop.
- E.g a statement to increment the loop counter at end of each iteration.
- body
- Body of loop contains the group of statement that needs to be executed in each iteration of the loop
- Must be enclosed within { }
Example of a simple For Loop
Below is an example of simple loop that prints out all ODD numbers less than 20
for i := 1; i <= 20 ; i = i+2 { fmt.Print(i, " ") }
- Init-Statement
i := 1
- We declare a variable
i
, and initialize it to1
at start of the loop - The scope of this variable is the For Loop only, i.e., it cannot be accessed outside the For loop.
- This is optional, and can be skipped.
- Condition-Expression
i <= 20
- Due to this condition, the loop will continue executing till the value of
i
is less than or equal to 20. - This is also optional, and can be skipped.
- Post-Statement
i = i+2
- At end of each iteration, the value of variable
i
is incremented by 2. - This is also optional, and can be skipped.
- Body of Loop
- Contains only a single statement –
fmt.Print(i, " ")
- This will print out the value of
i
, in each iteration of the loop
- Contains only a single statement –
If you execute the above For loop in a Go Program, you will see following output
1 3 5 7 9 11 13 15 17 19
3.2 Loop with only a condition (equivalent to a while loop in Java)
Many of you might be aware of while
Loops in Java
, which may look like below
while ( [some-condition-is-true] ) { [execute body] }
GoLang does not have any While
Loops. However we can write a variant of a For Loop that will exactly equivalent to a while loop.
To do that do following
- Remove the
init-statement
andpost-statement
from the for loop - Just put a
condition-expression
in the for loop
Following is an example of For Loop with only a condition
package main import ( "fmt" "math/rand" "time" ) func main() { i := 1 for i <= 20 { fmt.Print(i, " ") rand.Seed(time.Now().UnixNano()) i = i + rand.Intn(5) } }
As you can see in above example, the For loop only contains a condition-expression
, and no init-statement
or post-statement
.
One reason for writing loops like this would be
- We want the counter variable (
i
in this case), to be accessible outside the scope of For loop. If we had declared it usinginit-statement
, then it would have been accesible only within the scope of For loop. init-statement
andpost-statement
, are more complex (as in the scenario above)
3.3 Infinite loops
There are some scenarios, where we want to run an infinite loop, i.e., it keeps on executing forever, till the time the program is manually terminated.
A infinite loop looks like below
for { // body of the loop }
e.g.
for { fmt.Println("Printing forever..") }
Note that there is no condition-expression in this loop, so it never terminates.
A real life example of a inifinite For loop could be a Pinger application, which keeps pinging a server every 5 seconds to check if its available or not.
3.4 Nested for loops
You can also nest For loops within another For loop. e.g.
for x:=0; x < 3 ; x++ { // Outer For Loop for y:=0; y < 2; y++ { // Inner For Loop fmt.Printf("[%d:%d], ", x, y) } }
The ‘inner’ For loop will be executed for each iteration of the ‘outer’ For loop.
It would print below output
[0:0], [0:1], [1:0], [1:1], [2:0], [2:1],
3.5 Breaking from the loop
Normally a For loop terminates whenever the condition-expression
evaluates to false
. What if we want some control on how to exit the For loop, irrespective of what the value of condition-expression
is?
Some scenarios could be
- There is an error or invalid condition, and we want to exit the For loop (even if
condition-expression
evaluates totrue
. - We are running an infinite loop, and at certain point we want to exit the infinite loop.
We can do above by use of a break
statement. As soon as break
statement is executed, it will exit from the immediate enclosing For loop.
Below is an example of using break statement
for { //Generating a random number till 100 rand.Seed(time.Now().UnixNano()) num := rand.Intn(100) fmt.Print(num) if num % 2 != 0 { // Exit loop if number is Odd. fmt.Println("nEncountered an odd number. Exiting the loop") break; } // This will be printed at end of each for loop iteration fmt.Print(" --> Next --> ") }
It will print something like this (output will vary in each execution)
40 --> Next --> 88 --> Next --> 51 Encountered an odd number. Exiting the loop
As you can see from the output, as soon as an odd number is found, break statement exits the loop and no further statement of loop is executed.
3.6 Continuing in Loop
There are some scenarios where want to skip rest of the for loop execution (in current iteration), and start the next iteration immediately. We can do this by using continue
statement.
continue
statement allows us to
- Go back to the beginning of the For loop and continue next iteration.
- All statements from the
continue
statement to the end of the For loop, will be skipped in the current iteration - However
post-statement
andcondition-expression
of the For loop, will always get executed.
Consider the example below, where it only prints square of even numbers.
for i:=0; i < 10; i++ {
fmt.Print(" * ")
if i % 2 != 0 {
// If number is odd, continue to start of loop
continue
}
square := i * i
fmt.Print(square)
}
As you can see from the output below, as soon as it encounters a odd number, it skips the execution of remaining statements, and continues to next iteration of for loop.
* 0 * * 4 * * 16 * * 36 * * 64 *
In the next blog of the Learn Go tutorial series, we will look at Arrays and Slices in Go