Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Go for DevOps

You're reading from   Go for DevOps Learn how to use the Go language to automate servers, the cloud, Kubernetes, GitHub, Packer, and Terraform

Arrow left icon
Product type Paperback
Published in Jul 2022
Publisher Packt
ISBN-13 9781801818896
Length 634 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Authors (2):
Arrow left icon
John Doak John Doak
Author Profile Icon John Doak
John Doak
David Justice David Justice
Author Profile Icon David Justice
David Justice
Arrow right icon
View More author details
Toc

Table of Contents (22) Chapters Close

Preface 1. Section 1: Getting Up and Running with Go
2. Chapter 1: Go Language Basics FREE CHAPTER 3. Chapter 2: Go Language Essentials 4. Chapter 3: Setting Up Your Environment 5. Chapter 4: Filesystem Interactions 6. Chapter 5: Using Common Data Formats 7. Chapter 6: Interacting with Remote Data Sources 8. Chapter 7: Writing Command-Line Tooling 9. Chapter 8: Automating Command-Line Tasks 10. Section 2: Instrumenting, Observing, and Responding
11. Chapter 9: Observability with OpenTelemetry 12. Chapter 10: Automating Workflows with GitHub Actions 13. Chapter 11: Using ChatOps to Increase Efficiency 14. Section 3: Cloud ready Go
15. Chapter 12: Creating Immutable Infrastructure Using Packer 16. Chapter 13: Infrastructure as Code with Terraform 17. Chapter 14: Deploying and Building Applications in Kubernetes 18. Chapter 15: Programming the Cloud 19. Chapter 16: Designing for Chaos 20. Index 21. Other Books You May Enjoy

Looping in Go

Most languages have a few different types of loop statements: for, while, and do while.

Go differs in that there is a single loop type, for, that can implement the functionality of all the loop types in other languages.

In this section, we will discuss the for loop and its many uses.

C style

The most basic form of a loop is similar to C syntax:

for i := 0; i < 10; i++ {
     fmt.Println(i)
}

This declares an i variable that is an integer scoped to live only for this loop statement. i := 0; is the loop initialization statement; it only happens once before the loop starts. i < 10; is the conditional statement; it happens at the start of each loop and must evaluate to true or the loop ends.

i++ is the post statement; it occurs at the end of every loop. i++ says to increment the i variable by 1. Go also has common statements, such as i += 1 and i--.

Removing the init statement

We don't need to have an init statement, as shown in this example:

var i int
for ;i < 10;i++ {
     fmt.Println(i)
}
fmt.Println("i's final value: ", i)

In this, we declared i outside the loop. This means that i will be accessible outside the loop once the loop is finished, unlike our previous example.

Remove the post statement too and you have a while loop

Many languages have a while loop that simply evaluates whether a statement is true or not. We can do the same by eliminating our init and post statements:

var i int
for i < 10 {
     i++
}
b := true
for b { // This will loop forever
     fmt.Println("hello")
}

You might be asking, how do we make a loop that runs forever? The for loop has you covered.

Creating an infinite loop

Sometimes you want a loop to run forever or until some internal condition inside the loop occurs. Creating an infinite loop is as simple as removing all statements:

for {
     fmt.Println("Hello World")
}

This is usually useful for things such as servers that need to process some incoming stream forever.

Loop control

With loops, you occasionally need to control the execution of the loop from within the loop. This could be because you want to exit the loop or stop the execution of this iteration of the loop and start from the top.

Here's an example of a loop where we call a function called doSomething() that returns an error if the loop should end. What doSomething()does is not important for this example:

for {
     if err := doSomething(); err != nil {
          break
     }
     fmt.Println("keep going")
}

The break function here will break out of the loop. break is also used to break out of other statements, such as select or switch, so it's important to know that break breaks out of the first statement it is nested inside of.

If we want to stop the loop on a condition and continue with the next loop, we can use the continue statement:

for i := 0; i < 10; i++ {
     if i % 2 == 0 { // Only 0 for even numbers
           continue
     }
     fmt.Println("Odd number: ", i)
}

This loop will print out the odd numbers from zero to nine. i % 2 means i modulus 2. Modulus divides the first number by the second number and returns the remainder.

Loop braces

Here is the introduction of this rule: A for loop’s open brace must be on the same line as the for keyword.

With many languages, there are arguments about where to put the braces for loops/conditionals. With Go, the authors decided to pre-empt those arguments with compiler checks. In Go, you can do the following:

for {
     fmt.Println("hello world")
}

However, the following is incorrect as the opening brace of the for loop is on its own line:

for
{
     fmt.Println("hello world")
}

In this section we learned to use for loops as C style loops, as while loops.

You have been reading a chapter from
Go for DevOps
Published in: Jul 2022
Publisher: Packt
ISBN-13: 9781801818896
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 $19.99/month. Cancel anytime