TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Golang For Examples

These Go examples use the for-loop to iterate through numbers. Syntax and benchmarks are provided.

For-loop. Go has one loop: the for-loop.

But this loop can be used in many ways, to loop from a start to an end, or until a condition is reached.

With range, a keyword, we can iterate over more complex things like slices or maps. Range, used with for, helps us manage iteration.

An example. This code uses the classic for-loop where we begin at a certain number and end at another. After each body evaluation, the index is incremented (1 is added to it).

Syntax: The variable i is declared and initialized to 0. The ":=" syntax indicates that this is a new variable.

Semicolons: We separate the three clauses of this form of the for-loop with semicolons. Braces are used for the loop body.

Based on:

Golang 1.4

Golang program that uses for-loop from start to end

package main

import "fmt"

func main() {
    // Loop from 0 until 5 is reached.
    for i := 0; i < 5; i++ {
	// Display integer.
	fmt.Println(i)
    }
}

Output

0
1
2
3
4

Condition, while. There is no while keyword here, but the for-loop can be used as a while-loop. It continues while the condition specified after "for" is true.

Here: The variables "valid" and "i" are initialized. While "valid" is true, the loop continues iterating.

End: The loop terminates after the variable "i" is incremented to 3, and valid is set to false.

Golang program that uses for condition, while loop

package main

import "fmt"

func main() {
    valid := true
    i := 0

    // This loop continues while "valid" is true.
    for valid {

	// If i equals 3, set "valid" to false.
	if i == 3 {
	    valid = false
	}
	fmt.Println(i)
	i++
    }
}

Output

0
1
2
3

No condition. A for-loop can be specified with no condition. This loop continues infinitely until broken (as by a return or break statement).

Tip: This is the same as a "while true" loop in other languages. It is a loop that has no specified terminating condition.

Golang program that uses for, no condition

package main

import "fmt"

func main() {
    id := 10

    // This loop continues infinitely until broken.
    for {

	// Break if id is past a certain number.
	if id > 20 {
	    break
	}
	fmt.Println(id)
	id += 5
    }
}

Output

10
15
20

Range and slice. The range keyword is used with a for-loop. When we use range on a slice, all the indexes in the slice are enumerated.

So: The range of the three-element int slice here returns 0, 1 and 2. We use those to get elements from the slice.

Golang program that uses for and range, slice

package main

import "fmt"

func main() {
    // Create a slice of three ints.
    ids := []int{10, 21, 35}

    // Loop over range of indexes in the slice.
    for i := range ids {
	fmt.Println(ids[i])
    }
}

Output

10
21
35

Decrement. A loop can decrement from a higher number to a lower one. We often test for >= 0 in this case. The decrement statement uses two minus signs.

Golang program that uses for, decrements index

package main

import "fmt"

func main() {
    // Decrement loop.
    for i := 4; i >= 0; i-- {
	// Display loop index.
	fmt.Println(i)
    }
}

Output

4
3
2
1
0

A summary. The for-loop in Go has many purposes. We use one of its forms to iterate in many ways. With range, a helpful keyword, we iterate in a clear way over collections.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf