Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Go Programming - From Beginner to Professional - Second Edition

You're reading from  Go Programming - From Beginner to Professional - Second Edition

Product type Book
Published in Mar 2024
Publisher Packt
ISBN-13 9781803243054
Pages 680 pages
Edition 2nd Edition
Languages
Author (1):
Samantha Coyle Samantha Coyle
Profile icon Samantha Coyle

Table of Contents (30) Chapters

Preface Part 1: Scripts
Chapter 1: Variables and Operators Chapter 2: Command and Control Chapter 3: Core Types Chapter 4: Complex Types Part 2: Components
Chapter 5: Functions – Reduce, Reuse, and Recycle Chapter 6: Don’t Panic! Handle Your Errors Chapter 7: Interfaces Chapter 8: Generic Algorithm Superpowers Part 3: Modules
Chapter 9: Using Go Modules to Define a Project Chapter 10: Packages Keep Projects Manageable Chapter 11: Bug-Busting Debugging Skills Chapter 12: About Time Part 4: Applications
Chapter 13: Programming from the Command Line Chapter 14: File and Systems Chapter 15: SQL and Databases Part 5: Building For The Web
Chapter 16: Web Servers Chapter 17: Using the Go HTTP Client Part 6: Professional
Chapter 18: Concurrent Work Chapter 19: Testing Chapter 20: Using Go Tools Chapter 21: Go in the Cloud Index Other Books You May Enjoy

Command and Control

Overview

In this chapter, we’ll use branching logic and loops to demonstrate how logic can be controlled and selectively run. With these tools, you’ll have control of what you do and don’t want to run based on the values of variables.

By the end of this chapter, you will be able to implement branching logic using if, else, and else if; use switch statements to simplify complex branching logic; create looping logic using a for loop; loop over complex data collections using range; use continue and break to take control of the flow of loops; and use goto statements to jump to a labeled statement within a function.

Technical requirements

For this chapter, you'll require Go version 1.21 or higher. The code for this chapter can be found at: https://github.com/PacktPublishing/Go-Programming-From-Beginner-to-Professional-Second-Edition-/tree/main/Chapter02.

Introduction

In the previous chapter, we looked at variables and values and how we can temporarily store data in a variable and make changes to that data. We’re now going to look at how we can use that data to run logic in code, or not, selectively. “Logic” refers to the sequence of instructions that control how your program operates or processes data. This logic allows you to control how data flows through your software. You can react to and perform different operations based on the values in your variables.

The logic could be for validating your user’s inputs. If we were writing code to manage a bank account and the user asked to withdraw some money, we could check that they asked for a valid amount of money. We would check that they had enough money in their account. If the validation were successful, we would use logic to update their balance, transfer the money, and show a success message. If the validation failed, we’d show a message explaining...

if statements

An if statement is the most basic form of logic in Go. An if statement either will or will not run a block of code based on a Boolean expression. The notation looks like this: if <boolean expression> { <code block> }.

The Boolean expression can be simple code that results in a Boolean value. The code block can be any logic that you could also put in a function and are confined to the code block of that function. The code block runs when the Boolean expression is true. You can only use if statements within the scope of a function. In Go, the concept of “function scope” refers to the visibility and accessibility of variables and statements within a function. .

Exercise 2.01 – a simple if statement

In this exercise, we’ll use an if statement to control whether certain code will or will not run. We’ll define an int value that will be hardcoded, but in a real-world application, this could be user input. We’ll then...

Expression switch statements

While it’s possible to add as many else if statements to an if statement as you want, at some point, it’ll get hard to read.

When this happens, you can use Go’s logic alternative: switch. For situations where you would need a big if statement, switch can be a more compact alternative.

The notation for switch is shown in the following code snippet:

switch <initial statement>; <expression> {
case <expression>:
  <statements>
case <expression>, <expression>:
  <statements>
default:
  <statements>
}

The initial statement works the same in switch as it does in the preceding if statements. The expression is not the same because if is a Boolean expression. You can have more than just a Boolean in this expression. The cases are where you check to see whether the statements get executed. Statements are like code blocks in if statements, but with no need...

Loops

In real-world applications, you’re often going to need to run the same logic repeatedly. It’s common to have to deal with multiple inputs and give multiple outputs. Loops are the simplest way of repeating your logic.

Go only has one looping statement, for, but it’s a flexible one. There are two distinct forms: the first is used a lot for ordered collections such as arrays and slices, which we’ll cover more later. The sort of loop used for ordered collections looks as follows:

for <initial statement>; <condition>; <post statement> {
  <statements>
}

The initial statement is just like the one found in if and switch statements. An initial statement runs before everything else and allows the same simple statements that we defined before. The condition is checked before each loop to see whether the statements should be run or whether the loop should stop. As with an initial statement, condition also allows simple...

break and continue

There are going to be times when you need to skip a single loop or stop a loop from running altogether. It’s possible to do this with variables and if statements, but there is an easier way.

The continue keyword stops the execution of the current loop and starts a new loop. The post loop logic runs, and the loop condition statement gets evaluated.

The break keyword also stops the execution of the current loop and stops any new loops from running.

Use continue when you want to skip a single item in a collection; for instance, perhaps it’s okay if one of the items in a collection is invalid, but the rest may be okay to process. Use break when you need to stop processing when there are any errors in the data and there’s no value in processing the rest of the collection.

Here, we have an example that generates a random number between 0 and 8. The loop skips on a number divisible by 3 and stops on a number divisible by 2. It also prints...

goto statements

There may come a time when you want to skip certain logic within a function and go to a certain location within the function using the goto keyword. This may be accomplished using a label within the function and will result in a compilation error if attempting to use the goto label outside of the function scope.

goto statements are a way of adapting the Go control flow; however, they need to be used with caution as they can lead to difficulties in understanding function control flow and decrease code readability if used improperly. goto statements are used within the Go standard library in some cases, such as the math package, to make logic easier to read and reduce the need for unnecessary variables.

Exercise 2.12 – using goto statements

In this exercise, we’ll use goto in a function to show you how you can take control of it. We’re going to create a loop that keeps looping forever. This means we will have to stop it and exit manually...

Summary

In this chapter, we discussed logic and loops. These are the foundational building blocks to build complex software. They allow you to have data flow through your code. They let you deal with collections of data by letting you execute the same logic on every element of the data.

Being able to define the rules and laws of your code is the starting point of codifying the real world in software. If you are creating banking software and the bank has rules about what you can and can’t do with money, then you can also define those rules in your code.

Logic and loops are essential tools that you’ll use to build all your software.

In the next chapter, we’ll look at Go’s type system and the core types it has available.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Go Programming - From Beginner to Professional - Second Edition
Published in: Mar 2024 Publisher: Packt ISBN-13: 9781803243054
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}