Skip to main content

Control Statements in Golang

The beauty of every programming language is defined by the flow of the program i.e by the Control Statements!. Yes, Control statements defines the flow of the program through the blocks of  statements defined. Go language provides control statements as like other languages but with different usage possibilities.

Control Statement
Source: www.programiz.com

Types Of Control Statements

There are three types of control statements available with Golang: Conditional, Unconditional and Loop.

Conditional Statements

Conditional statements are statements which would execute the branch of statements conditionally. They are if, if-else , else-if and switch.

If statement

if control statement controls the execution of the branch of statements based on the condition given. The syntax is,

if conditions { 
// statements to be executed 
}

Let's look at the below example

if age == 5 { 
  fmt.Println("Come back when you turn 6 to join 1st standard!")
}

In Golang, we can have initialization statement right before the conditional statement separated by semicolon

if canJoin:= canJoinFirstStandard(); canJoin < 6 { 
  fmt.Println("Come back when you turn 6 to join 1st standard!")
}

If-Else statement

If you wanted to do two different things based on the result of expression, you can use if-else construct.

if canJoin := canJoinFirstStandard(); canJoin < 6 { 
  fmt.Println("Come back when you turn 6 to join 1st standard!")
} else {
  fmt.Println("You are eligible to join 1st standard!")
}

Multiple If-Else statements

When you wanted to handle multiple conditions, you can chain if-else statements as shown below,

if canJoin := canJoinFirstStandard(); canJoin < 6 { 
  fmt.Println("Come back when you turn 6 to join 1st standard!")
} else if canJoin < 6 && canJoin > 5 {
  fmt.Println("You are eligible to join UKG!")
} else if canJoin < 5 && canJoin > 4 {
  fmt.Println("You are eligible to join LKG!")
} else if canJoin < 4 && canJoin > 3 {
  fmt.Println("You are eligible to join Nursery!")
} else {
  fmt.Println("You are 👶!")
}

Note that the canJoin variable could be accessible only in the if-else blocks.

Switch statement

switch statements could be used when you wanted to execute multiple blocks of statements for the given conditional expression. There are two forms of switch statements namely expression switches and type switches.

The expression switch would have cases with expression and to be compared with the value of the switch expression. Whereas the type switch would have cases with types and to be compared with the type returned from the switch expression.

switch age := getAge(); age {
 default: 
     fmt.Println("You are 👶!")
 case 3, 4: 
     fmt.Println("You are eligible to join Nursery or LKG!")
 case 5: 
     fmt.Println("You are eligible to join UKG!")
 case 6: 
     fmt.Println("You are eligible to join 1st standard!")
}

The above code snippet is an example for switch expression form where we evalute to get the age and compare with the cases

To work with types, here is an example,

switch gimmy.(type) {
 default: 
     fmt.Println("This is 👱!")
 case Dog: 
     fmt.Println("This is 🐶!")
 case Cat: 
     fmt.Println("This is 🐱!")
 case Cow: 
     fmt.Println("This is 🐄!")
}

Here the type of gimmy is evaluated and compared with the types used in the cases i.e the type of gimmy is compared against the types defined by the user Dog, Cat and Cow.

switch expression can be empty as shown below.

switch {
 default: 
     fmt.Println("You are 👶!")
 case age < 4 && 3 > age: 
     fmt.Println("You are eligible to join Nursery or LKG!")
 case age < 5 && 4 > age: 
     fmt.Println("You are eligible to join UKG!")
 case age < 6 && 5 > age: 
     fmt.Println("You are eligible to join 1st standard!")
}

When there is nothing in the switch, it would be considered as true value and compared with the case expressions with yields to boolean i.e either true or false

In Golang, the switch construct would execute the matching case and exit immediately by default. So there is no break kind of keyword to break the flow. But instead it has fallthrough keywork to continue to execute only the next case from the matching case.

age := 4
switch age {
 default: 
     fmt.Println("You are 👶!")
 case 3, 4: 
     fmt.Println("You are eligible to join Nursery or LKG!")
     fallthrough
 case 5: 
     fmt.Println("You are eligible to join UKG!")
 case 6: 
     fmt.Println("You are eligible to join 1st standard!")
}

When the switch expression age matches the case expression value 3, 4, it would execute the statements in that case and continue to execute only the next case.

The output to the above switch type would be,

You are eligible to join Nursery or LKG!
You are eligible to join UKG!

Note that the fallthrough could not be used in the type switches.

Unconditional Statement

Unconditional statements are executed without a condition to evaluated. In Golang, there is goto keyword to make unconditional statements.

func someFunc() {
    i := 0
    ThisLine:   // label ends with ":"
    fmt.Println(i)
    i++
    goto ThisLine // jump to label "ThisLine"
}

If you look at the above code, the goto keyword is used to uncoditionally jump to some part of the same scope and execute the statements. There should be a label followed by the goto keyword. The label is case sensitive and should be present somewhere in the same scope. The goto would work only within the current block.

Check the below example,

func someFunc() {
    i := 0
    ThisLine:   // label ends with ":"
    fmt.Println(i)
    i++
    if i % 2 == 0 {
        goto ThisLine // This is invalid
    }
}

The goto statement defined in the if block is invalid as it jumps to label "ThisLine" which is outside the scope.

Loop Statements

Loop statements are used to execute the statement blocks repeatedly. The for statement could be used in three different ways.

The first way is to use only the condition in the for statement as shown in the below snippet.

age := 0
for age < 3 {
   fmt.Println("You are 👶!")
   age++
}

The above code would output as shown below,

You are 👶!
You are 👶!
You are 👶!

We can use the for statement as we use in other languages as well. See the below example where we have for statement with initializer, condition and a statement which would be executed after the execution of the each iteration.

for age := 0; age < 3; age++ {
   fmt.Println("You are 👶!")
}

The above code would produce the same output as the for statement with only conditions.

For statement with range clause

The Golang has new keyword called range which would be used with the for loop to iterate through string, array, slice, collections and maps.

numbers := []int{1, 2, 3, 4, 5}
for i, num := range numbers {
   fmt.Printf("The index of %d is %d\n", num, i)
}

Here we have an array of 5 numbers from 1 to 5. and when we use the range with for loop, the range returns the index or key (if it is map) and the value. The output for the above would be,

The index of 1 is 0
The index of 2 is 1
The index of 3 is 2
The index of 4 is 3
The index of 5 is 4

The range keyword could be used with channels as well.

Break and Continue in For loops

As like other languages, break and continue are supported by Golang as well. The break keyword would be used to break the loop while the continue would transfer the control to the starting point of the for loop avoiding the next lines.

num := 0
for {
   num += 1
   if num >= 10 {
      break
   }

   if num %2 == 0 {
      continue
   }
   fmt.Println("Odd number: ", num)
}


The output of the above code is,

Odd number:  1
Odd number:  3
Odd number:  5
Odd number:  7
Odd number:  9

The code snippet printed only Odd numbers because when the num is even then the control would be transferred to starting line and if it is odd then the number would be printed in the console. Once the num reaches 10 then the for loop would break.

Conclusion

In this post, we have discussed about the control statements offered by the Golang.

Thanks for reading 🙏 Comments are welcome 👍

Comments

Popular posts from this blog

How to start with Go Language - A Google's Programming Language

It's been always fun to start programming with a brand new language. And, as a Programmer, it's absolutely worth to keep you updated with the new languages as you come across.

Every programming language in this world is been designed to solve a problem in mind. So learning a new language would help you to solve your problem efficiently if the language offers flexibility to do so.

I am going to share the knowledge on the new language; atleast for me 😉 (released on 10 November 2009) which i have explored on. The name of new language is Go. Yes it is Google's language; Golang.

Will see what Google says about the new Language,
Go is a statically typed, compiled language in the tradition of C, with memory safety, garbage collection, structural typing, and CSP-style concurrency. Yes, Go language is mainly designed to deal with morden days problems in the computing world. The Golang has the built-in feature of concurrency i.e deal with multiple tasks at same time which would le…

Variable declarations in Go language

Every programming language in this world provides options to declare and define variables and used by parts of the program. So Go does the same.

The wiki states that a variable is
a symbolic name associated with a value and whose associated value may be changedBut in more technical way, a variable is a memory location with name which might hold values and may change later.


Go provides different options to declare and define the variables. Let's see how we can declare variable in Golang.
Variable declarationA variable in go could be declared as follows,
package main import "fmt" var a = "has some value" func main() { fmt.Println(a) } Here the variable a is declared and initialized with the value "has some value". The type of the variable is inferred from the value been assigned.
Supported Types in GolangGo supports the following primitive types

BaseTypesDescriptionNumerics uint, int (8,16,32,64 bits), float (32, 64 bits),
 complex with 64, 128 bits, byt…