Looping in Go Programming Language

Go language has only one looping construct, that is for. There are three forms of for loops in Go. For can be used with single condition much like while loop in other programming language, a “for” clause which much like for loop in c language, and a “range” clause which is much like “for i in range” in python

For with single condition

Following simple program prints 0 to 9 numbers using for with single condition will demonstrates using of for statement much like while

package main

import "fmt"

func main() {
	n := 0
	for n < 10 {
		fmt.Printf("%v\t", n)
		n++
	}
}
0 1 2 3 4 5 6 7 8 9

For Loop

For statement with for clause which is regular for loop that we see in other programming languages (like for loop in c) . Syntax is as follows

for [ InitStmt ] ; [ condition ] ; [ PostStmt ]  { Statements/Body }

InitStmt is executed before the first iteration which contain typically the initialization of variable. PostStmt is executed after every iteration before checking the condition. Anything in InitStmt, condition and PostStmt are optional, if omitted semicolons (;) are required.

Writing a program to print 0 to 9 using for loop with for clause

package main

import "fmt"

func main() {

	for n := 0; n < 10; n++ {
		fmt.Printf("%v\t", n)
	}
}
for cond {} is same as for ; cond ; {}

forever loop or while true can be created using for without using any condition. for {} is same as for true {}

for with range clause

for range syntax is used to iterate seamlessly over all elements of string, array, slice, map or values from channel. For each iteration value from range expression (string, array, slice, or pointer to array/slice etc) is assigned to iteration variable if present

Syntax for loop with range clause

for x, y := range expression { ... } 

Where x,y are iteration variables. Number of iteration variables to be used depends on what range expression returns. For channels at most one iteration variable is used and for array, slice, string and map at most two iteration variables are permitted

Simple program to print code points of characters in given string “for range”

package main

import "fmt"

func main() {

	var greeting string = "hello world"
	for _, s := range greeting {
		fmt.Printf("%d \t ", s)
	}
}

Variables that are declared but not used raise exception. Underscore (_) is used for throw away variables

104 101 108 108 111 32 119 111 114 108 100

Default image
neotam
Naveen T aka neotam. Programming language agnostic, Software architect, Python expert, Networking & DevOps engineer & consultant with 7+ years of experience in creating serious web applications, real time event-driven non blocking applications and database driven applications ranging from small scale to enterprise grade. website
Leave a Reply