Using usage of golang while loop
Go does not offer the while keyword for writing while loops but allows you to use a for loop instead of a while loop.
A while loop in Go is a loop construct, where a block of code will be executed until a condition turns to false. While loops are mostly used in scenarios where we are not certain how many loop cycles we need. Unlike other programming languages like Python which have a while keyword to define a while loop, Go uses the for loop construct to define a while. In Go a basic loop would look like below.
for initialization; condition expression post statement {
code to execute
}
Here,
- An
init
statement: This statement is executed before the first iteration starts. (Each time the for statement executes the statements contained within it is called an iteration.) - A
condition
expression: This expression is evaluated before the iteration starts to determine if the iteration should continue. - A
post
statement: This statement is evaluated at the end of each iteration.
However, the for loop can also emulate a do...while
loop, which can be found in other programming languages.
As an example, the following Go code is equivalent to a do...while(anExpression)
loop:
for ok := true; ok; ok = anExpression {
}
As soon as the ok variable has the false value, the for loop will terminate.
Understanding syntax of Go While Loop
Now , a Go while will make use of the for keyword and the initialization and omit the condition expression and the post statement. Below is the Go while loop syntax.
for condition {
code to execute
}
Example
package main
import "fmt"
func main() {
count := 0
for count < 5 {
fmt.Println("Count >>>", count)
count += 1
}
}
Explanation
In the above code sample, we first initialize the start of the loop using the count
variable. The next line defines the beginning of the while loop. The condition in this while loop (count < 5)
will determine the number of loop cycles to be executed.
As long as the condition returns true
, the block of code between {}
will be executed. Inside the while loop body, we increase the count variable (count += 1)
after every loop. It's important to note that without this statement, the while loop will run forever, which in many cases is undesirable.
We will learn how to use the while loop with different data structures.
Output
$ go run main.go
Count >>> 0
Count >>> 1
Count >>> 2
Count >>> 3
Count >>> 4
Loop through struct elements using golang while loop
Go struct data structure is a basic data store that is made up of a collection of fields. We can use Go while loop with the struct types when we are not sure how many fields we need to loop through. Other Go loops like the basic for loop
in Go can also be used to loop through struct fields. For more information about that please read this article. Since while loops in Go require a condition, we need to find the number of fields inside a struct to control the loop, otherwise the loop will execute forever.
Example
package main
import (
"fmt"
"reflect"
)
type car struct {
Name string
Color string
Price int64
}
func main() {
c := car{
Name: "Subaru Outback",
Color: "Black",
Price: 9600,
}
values := reflect.ValueOf(c)
typesOf := values.Type()
size := values.NumField()
count := 0
for count < size {
fieldName := typesOf.Field(count).Name
fieldValue := values.Field(count).Interface()
fmt.Printf("%s : %v\n", fieldName, fieldValue)
count += 1
}
}
Explanation
In our preceding example, we define a struct with Name
, Color
and Price
fields of type string
, string
and integer
respectively. In the main function, we create an instance of a car struct
. The values
variable stores the runtime data. This is made possible by the reflect Go package. We can use the values
variable to access the field name field values and the number of fields from the car
instance. We then get the number of fields from the values variable using size := values.NumField()
statement and declare the count variable with its initial value being 0 using the count := 0
statement.We then start the while loop using for count < size
statement. While looping we pull the field name and its corresponding field value then print them on the console.
Output
$ go run main.go
Name : Subaru Outback
Color : Black
Price : 9600
Loop through Maps using golang while loop
Go Map is a collection of key-value pairs that are unordered, and provides developers with quick lookup, update and delete features. Go Maps can be used with a while loop , through its key-value pairs. Below is an example on how to use the while loop to iterate over Map key-value pairs.
Example
package main
import (
"fmt"
"reflect"
)
func main() {
user := map[string]string{
"firstName": "Mike",
"lastname": "joe",
"email": "mikejoe@golinuxcloud.com",
}
count := 0
keys := reflect.ValueOf(user).MapKeys()
for count < len(keys) {
key := fmt.Sprint(reflect.ValueOf(keys[count]).Interface())
value := user[key]
fmt.Printf("Key : %s Value : %s \n", key, value)
count += 1
}
}
Explanation
In the above code sample, we create a user
instance of type map. We define the count
variable that defines the start of the loop. We then define the keys
variable that stores keys found in the user map. In the while loop , we define a condition that checks if the count variable is less than the length of the keys found in the map. When the condition returns true, we store each respective key and convert it to string types using this line fmt.Sprint(reflect.ValueOf(keys[count]).Interface())
. To obtain the value for the key, we use the code value := user[key]
. The print statement prints the key and value from the map.Please note that the order of the key value pair is unordered. Finally we ensure to increment the count value by 1 every iteration using the code count += 1
Loop through slice elements using while loop
In Go, a slice is dynamically sized, flexible array type and the are more common than the arrays. We can use a while loop to iterate through elements of a slice. The below example demonstrates using a while loop in Go to loop through items in a slice.
Example
package main
import "fmt"
func main() {
numbers := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}
count := 0
for count < len(numbers) {
fmt.Printf("Index : %d ==> Item : %d \n", count, numbers[count])
count += 1
}
}
Explanation
In the preceding example, we initialize a slice with items of type int
and a count
variable with its initial value being 0. We use the count variable to keep track of the indexes in the int
slice. We then start the while loop that checks if the count
is less than the number of items in the slice. Using the Printf()
function, we print the index and the value of each item in the slice. At the end, we ensure to increment the value of count after every iteration, without which the loop will iterate forever.
Output
$ go run main.go
Index : 0 ==> Item : 1
Index : 1 ==> Item : 2
Index : 2 ==> Item : 3
Index : 3 ==> Item : 4
Index : 4 ==> Item : 5
Index : 5 ==> Item : 6
Index : 6 ==> Item : 7
Index : 7 ==> Item : 8
Index : 8 ==> Item : 9
Loop through string characters using while loop
String in Go is a sequence of characters , for example “Golinuxcloud.com” is a sequence of characters. We can use a while loop to iterate over a string while keeping track of the size of the string. In the following example , we use the while loop to iterate over a Go string.
Example
package main
import (
"fmt"
)
func main() {
goSite := "Hello, World!"
count := 0
for count < len(goSite) {
fmt.Printf("%d : %c \n", count, goSite[count])
count += 1
}
}
Explanation
We define the goSite
variable that stores the "Hello, World!"
string and a count
variable that will keep track of the indexes in the string(<b>"</b>Hello, World!"
). Using the Printf
function from the fmt package
, we print the indexes with their respective characters. We finally increment the count variable, without which the while loop will iterate forever.
Output
$ go run main.go
0 : H
1 : e
2 : l
3 : l
4 : o
5 : ,
6 :
7 : W
8 : o
9 : r
10 : l
11 : d
12 : !
Loop through items of interface type using while loop
In Go, every type implements an empty interface. An empty interface is an interface without any methods. We can loop through a slice of items of type interface using the Go while loop.
Example
package main
import "fmt"
func main() {
items := [5]interface{}{"January", 3.244, false, 99, map[string]int{"age": 23}}
count := 0
for count < len(items) {
fmt.Printf("Index ==> %d Type ==> %T Value ==> %v \n", count, items[count], items[count])
count += 1
}
}
Output
$ go run main.go
Index ==> 0 Type ==> string Value ==> January
Index ==> 1 Type ==> float64 Value ==> 3.244
Index ==> 2 Type ==> bool Value ==> false
Index ==> 3 Type ==> int Value ==> 99
Index ==> 4 Type ==> map[string]int Value ==> map[age:23]
Loop through elements and store in golang channel
In Go, channels are typed conduits through which values are sent and received using the channel operator <-
. In the next example, we will use the Go while loop to loop through strings and send them to a channel.
Example
package main
import "fmt"
func testChannel(c chan string) {
colors := [5]string{"red", "yellow", "blue", "green", "black"}
count := 0
for count < len(colors) {
c <- colors[count]
count += 1
}
close(c)
}
func main() {
c := make(chan string, 10)
go testChannel(c)
for value := range c {
fmt.Println(value)
}
}
Explanation
In the above example, we create a slice of strings that get sent one by one to a channel of type string using a while loop. The loop will iterate until the count variable is no longer less than the number of strings in the colors slice.
Output
$ go run main.go
red
yellow
blue
green
black
Run infinite loop using while loop
An infinite while loop is a loop that does not have a stopping condition. The loop will continue iterating forever unless it is stopped by an external entity. In the next example we will create a while loop that sends elements and another receiving channel that prints endlessly.
Example
package main
import (
"fmt"
"time"
)
func msgSender(c chan string) {
for {
msg := fmt.Sprint("https://www.golinuxcloud.com is the best Go site")
time.Sleep(1 * time.Second)
c <- msg
}
}
func main() {
c := make(chan string)
go msgSender(c)
for value := range c {
fmt.Println(value)
}
}
Explanation
In the above example , we declare an infinite loop using the for
keyword without declaring a condition that will be checked. Messages will be sent into the channel after every one second. In the main function, the messages will be printed to the console after every second. The loop will continue iterating until the you stop the script from running by pressing the CTRL + C
on the keyboard.
Output
$ go run main.go
https://www.golinuxcloud.com is the best Go site
https://www.golinuxcloud.com is the best Go site
https://www.golinuxcloud.com is the best Go site
^Csignal: interrupt
Using do..while loop (repeat until) in golang
As we discussed briefly during the introduction section, in golang we can use for
loop and execute a do..while
condition. In this example we will ask for user input and until we get a certain pre-defined input, the loop should repeat itself.
package main
import "fmt"
var input int
func main() {
for ok := true; ok; ok = (input != 2) {
n, err := fmt.Scanln(&input)
if n < 1 || err != nil {
fmt.Println("invalid input")
break
}
switch input {
case 1:
fmt.Println("hi")
case 2:
// Do Something
default:
fmt.Println("I will print this if no match found!")
}
}
}
Summary
While loops are a key iterating feature in Go, and are mostly used in situations where we are not sure how many iterations we need. When using a while loop , it's important to include a condition that will stop the loop , otherwise the loop will run forever. In this article, we learn how to use while loops through different data structures.
References
For is Go's "while" - A Tour of Go