Apps/Gaming

Understand control structures in Go

In every programming language, control structures help to form the important building blocks of the programming logic. Hence, a clear understanding of its syntax is a prerequisite. Someone familiar with C / C ++ will find many similarities in the control structures that Go generally provides. Note, however, that Go brought up some new ideas. This article gives an insight into the use of control structures in Go programming.

Control structures in Golang

The control structures provide the means to control or manipulate the flow of the program. Imagine a jet of water flowing downwards; We can meander its way through a curved path or maybe create a loop through which water can pass. However, we cannot change its downward flow, but between the beginning and the end of the stream we can play with its route or control the flow. The control structures in Go, such as if conditions, for loops, switch statements, etc., also help to control the program flow. The beginning and end – or termination – of the program cannot be changed, because a program that starts executing has to stop somewhere at some point. The control structures only control the flow of the program between start and stop.

Programs are nothing more than manifestations of an algorithm, and an algorithm is the logical explanation you provide in order to solve a given problem. Syntactically, this control structure actually helps in programming languages ​​like Go in spreading the logic to solve a problem. There are usually three types of control structures that we find in any programming language. They are:

  • Sequential flow
  • Conditional flow
  • Iterative process

Read: Understand math operators in Go

Sequential flow control structure in Go

The sequential flow is the simplest control structure in Go and follows a straight path. Imagine a stream of water flowing straight ahead. In programming, instructions are executed one after the other in an obvious order. While it may seem like a very basic pattern, many complex algorithms are expressed this way, and code modules are actually executed numbered. Consider the following:

Example: Statement 1 Statement 2 Statement 3 Statement 4 Statement 5

Conditional flow control structure in Go

Conditional flows are best viewed as a way to choose one from another. At some point in the code flow we have to choose a particular path. The logic is expressed in such a way that the outcome or outcome of the code varies as one path is preferred over another. There may be one or more conditions based on which the flow of code changes direction. Imagine a road junction where we have to decide which route to take. Consider the following pseudocode:

Example: If Then: Statement 1 Else If then: Statement 2 … Else Statement 5 End If

Iterative flow control structures in Go

The iterative flow uses the logic of loops. Here there is a single entry point based on certain conditions that executes the instructions within the iterative block. In each iterative step, it checks the condition whether it is still fulfilled or not and only breaks out of the loop in the step if the condition is no longer fulfilled – or returns a Boolean

Example: For I = 1 To N Statement 1 … Statement 5 I = I + 1 End For

Read: How to use strings in Go

Code example for sequential flow in Go

A simple illustration of a sequential flow is to write a program that counts the natural numbers 1 through 10 and prints each one on a separate line. The code in Go would be something like this:

Package main import “fmt” func main () {fmt.Println (1) fmt.Println (2) fmt.Println (3) fmt.Println (4) fmt.Println (5) fmt.Println (6) fmt.Println (7) fmt.Println (8) fmt.Println (9) fmt.Println (10)}

Or we could write the following Go-Code instead:

fmt.Println (`1 2 3 4 5 6 7 8 9 10`)

This latter syntax is very typical of Go and cannot be found in C / C ++, although it may look like a distant brother in appearance.

In either case, the code flow is sequential. Also note that this type of code is tedious; Imagine the numbers are huge – then it’s not very efficient to write a single line every time we need to print. In fact, it can be better expressed in terms of an iterative flow of code.

Example of an iterative flow code in Go

The iterative process in Go is implemented using a for statement. It enables a block of code to be executed repeatedly. So if we rewrite the above code it looks like this:

Package main import “fmt” func main () {for i: = 1; i <= 10; i ++ {fmt.Println (i)}}

Watch as the for loop begins with the initiation of a value i: = 1 to begin the iteration, then the control flow checks the condition and, if it is met, enters the loop and executes the fmt.Println ( i) statement. After printing once, the control goes to the increment section of the loop – the i ++ statement – and checks again whether the condition i <= 10 is met or not. If it is true, the block of code is executed inside the for loop and then goes back to the i ++ section and the conditions section of the for loop. This is repeated until the condition is no longer met and finally breaks out of the loop. To put it categorically:

Step 1: initialize a variable (i: = 1 in our case);
Step 2: Conditional expression (i <= 10) that is either true or false;
Step 3: expression (i ++, increment in our case)
Step 4: code block to be executed if the result of the conditional statement (step 2) is true. Otherwise, cancel the for loop.
Step 5: Repeat the sequence: Step 3, then Step 2 and Step 4.

If you are familiar with the C / C ++ loop statements, there are three types: for, while, and do … while. While there is any subtlety in using any of the three subtleties of convenience, it is only one choice among equivalent capabilities. This mix of choices is completely eliminated in Go and only offers one type, namely the for loop. Go uses two types of syntax for statements: a simple for statement (as we’ve seen), another is the for… range statement. Here is a quick example of how it can be used for range in Go:

Package main import (“fmt” “unicode”) func main () {Greetings: = “Hello! Friends” for index, ch: = range Greetings {fmt.Printf (“% c”, unicode.ToUpper (ch)) index ++} }

Read: Arrays and Slices in Go

Example of conditional expiration code in Go

As we can see, the for loop has a conditional expression that acts as an entry store, but there are statements that determine the flow of code based on a certain condition. The if statements do this. Let’s modify the program to print 1-10 numbers and print odd or even based on a condition:

func main () {for i: = 1; i <= 10; i ++ {if i% 2 == 0 {fmt.Println (i, "is EVEN")} else {fmt.Println (i, "is ODD")}}}

Whether a number is ODD or EVEN is decided by the expression i% 2. If the number is divided by 2 and has a remainder of 0, the number is EVEN, otherwise it is odd. Depending on whether the result of the conditional statement i% 2 == 0 is true or false, the execution path of the code is now changed. Of course we can have multiple / nested if..else statements like this:

if i% 2 == 0 {// do something} else if i% 3 == 0 {// do something} else if i% 5 == 0 {// do something} else if i% 9 == 0 { // do something} else {// do something}

The point is, the conditional statements can change the flow of control according to the outcome of a condition.
Sometimes multiple if … else conditional statements are an inconvenient way to write code. Instead, we can write Go switch statements to take advantage of the code flow, as shown here:

Number: = 10 switches {case number < 100: fmt.Println("Less than 100") case num > 100: fmt.Println (“greater than 100”) Standard: fmt.Println (“equal to 100”)}

Here is another example of a switch statement in Go:

Package main import (“fmt” “math / rand” “time”) func main () {deck: = []string {“spade”, “heart”, “club”, “diamond”} cards: = []string {“Ace”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “Jack”, “Queen”, “King”} randIndex: = rand.New (rand.NewSource (time.Now (). UnixNano ())) switch d: = deck[randIndex.Intn(4)]; d {case “spade”: fmt.Println (cards[randIndex.Intn(13)], “SPADE”) “club” case: fmt.Println (cards[randIndex.Intn(13)], “CLUB”) Case “Heart”: fmt.Println (cards[randIndex.Intn(13)], “HEART”) “Diamond” case: fmt.Println (cards[randIndex.Intn(13)], “DIAMOND”) Standard: fmt.Println (“OOPS !!”)}}

Final thoughts on control structures in Go

So there are three basic control structures in Go: a simple sequential process, for loops for the iterative process, and if conditions and switch statements. In fact, these three suit the needs of the programmer. In contrast to C / C ++, Go has trimmed the syntaxes to the bare minimum instead of having too many options. However, Go is still a toddler and has miles to go to be compared to C / C ++. It’s worth noting, however, that programmers like simplicity, and Go aptly delivers it. Perhaps this is one of the main reasons for its popularity.

Read: Dealing with bugs in Go

Related posts

Project management kick off meetings

TechLifely

An Introduction to Kubernetes

TechLifely

How to improve your mobile game with narrative – part 1

TechLifely

Leave a Comment