<< Back to GO
Golang for Loop Examples: Foreach and While
Use the for-loop to iterate through numbers. Look at foreach and while loops.For-loop. Go has 1 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 3 clauses of this form of the for-loop with semicolons. Braces are used for the loop body.
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, break. 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.
rangeSo: 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
Foreach loop. Golang does not have a foreach keyword. But we can use a foreach loop by receiving 2 values in a for-range loop. We ignore the first, and the second is each element's value.
Golang program that uses foreach loop
package main
import "fmt"
func main() {
// Two strings in a slice.
animals := []string{"bird", "frog"}
// Loop over each element directly (foreach loop).
// ... Ignore the first pair of each returned pair (the index).
for _, animal := range animals {
fmt.Println(animal)
}
}
Output
bird
frog
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
Continue. This keyword ends the current iteration of a loop, but then the next iteration begins as usual. Unlike break, the loop itself is not terminated.
Here: When an element in the int slice equals 10, we use continue to stop processing of the current iteration.
Golang program that uses continue
package main
import "fmt"
func main() {
elements := []int{10, 20}
for i := range elements {
// If element is 10, continue to next iteration.
if elements[i] == 10 {
fmt.Println("CONTINUE")
continue
}
fmt.Println("ELEMENT:", elements[i])
}
}
Output
CONTINUE
ELEMENT: 20
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.
Built-Ins
Related Links:
- Golang strconv, Convert Int to String
- Golang Odd and Even Numbers
- Golang Recover Built In: Handle Errors, Panics
- Learn Go Language Tutorial
- Golang html template Example
- Golang http.Get Examples: Download Web Pages
- Golang container list Example (Linked List)
- Golang base64 Encoding Example: EncodeToString
- Golang os exec Examples: Command Start and Run
- Golang String Between, Before and After
- Golang os.Remove: Delete All Files in Directory
- Golang First Words in String
- Golang flag Examples
- Golang Regexp Find Examples: FindAllString
- Golang Regexp Examples: MatchString, MustCompile
- Golang Index, LastIndex: strings Funcs
- Golang Compress GZIP Examples
- Golang Interface Example
- Golang 2D Slices and Arrays
- Golang Sscan, Sscanf Examples (fmt)
- Top 41 Go Programming (Golang) Interview Questions (2021)
- Golang Padding String Example (Right or Left Align)
- Golang Equal String, EqualFold (If Strings Are the Same)
- Golang map Examples
- Golang Map With String Slice Values
- Golang Array Examples
- Golang Remove Duplicates From Slice
- Golang If, Else Statements
- Golang ParseInt Examples: Convert String to Int
- Golang Strings
- Golang strings.Map func
- Golang bufio.ScanBytes, NewScanner (Read Bytes in File)
- Golang Built In Functions
- Golang bytes.Buffer Examples (WriteString, Fprintf)
- Golang Bytes: Slices and Methods
- Golang Caesar Cipher Method
- Golang Chan: Channels, Make Examples
- Golang Math Module: math.Abs, Pow
- Golang Reverse String
- Golang Struct Examples: Types and Pointers
- Golang path and filepath Examples (Base, Dir)
- Golang Substring Examples (Rune Slices)
- Golang Suffixarray Examples: New, Lookup Benchmark
- Golang switch Examples
- Golang Convert Map to Slice
- Golang Convert Slice to String: int, string Slices
- Golang Const, Var Examples: Iota
- Golang ROT13 Method
- Golang strings.Contains and ContainsAny
- Golang rand, crypto: Random Number Generators
- Golang String Literal Examples (Repeat Method)
- Golang ToLower, ToUpper String Examples
- Golang Trim, TrimSpace and TrimFunc Examples
- Golang Join Examples (strings.Join)
- Golang Len (String Length)
- Golang Convert String to Rune Slice (append)
- Golang JSON Example: Marshal, Unmarshal
- Golang Replace String Examples: Replacer, NewReplacer
- Golang nil (Cannot Use nil as Type)
- Golang Slice Examples
- Golang ListenAndServe Examples (HandleFunc)
- Golang Fibonacci Sequence Example
- Golang Time: Now, Parse and Duration
- Golang bits, OnesCount (Get Bitcount From Int)
- Golang Fprint, Fprintf and Fprintln Examples (fmt)
- Golang Func Examples
- Golang csv Examples
- Golang Fields and FieldsFunc
- Golang unicode.IsSpace (If Char Is Whitespace)
- Golang fmt.Println Examples
- Golang for Loop Examples: Foreach and While
- Golang ioutil.WriteFile, os.Create (Write File to Disk)
- Golang File Handling
- Golang range: Slice, String and Map
- Golang Readdir Example (Get All Files in Directory)
- Golang Sort Slice: Len, Less, Swap in Interface
- Golang Get Lines in File (String Slice)
- Golang Split Examples (SplitAfter, SplitN)
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