The Wayback Machine - https://web.archive.org/web/20241127011819/https://www.geeksforgeeks.org/how-to-use-for-and-foreach-loop-in-golang/
Open In App

How to use for and foreach loop in Golang?

Last Updated : 23 Nov, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There is only one looping construct in Golang, and that is the for loop. The for loop in Golang has three components, which must be separated by semicolons (;), those are: 

  • The initialization statement: which is executed before the first iteration. e.g. i := 0
  • The condition expression: which is executed just before every iteration. e.g. i < 5
  • The Post statement: which is executed at the end of every iteration. e.g. i++

There is no need for any parentheses for enclosing those three components, but to define a block we must use braces { }.

for i := 0 ; i < 5 ; i++{
         // statements to execute......
}

The initialization and post statements are optional.

i:=0
for ; i < 5;{
i++
}

You can use for loop as while loop in Golang. Just drop all the semicolons. 

i := 0
for i < 5 {
i++
}

Infinite Loop: If there is no condition statement, the loop becomes an infinite loop. 

for {
}

Example:
 

Go




package main
 
import "fmt"
 
// function to print numbers 0
// to 9 and print the sum of 0 to 9
func main() {
 
    // variable to store the sum
    sum := 0
 
    // this is a for loop which runs from 0 to 9
    for i := 0; i < 10; i++ {
 
        // printing the value of
        // i : the iterating variable
        fmt.Printf("%d ", i)
 
        // calculating the sum
        sum += i
    }
    fmt.Printf("\nsum = %d", sum)
}


Output:
 

0 1 2 3 4 5 6 7 8 9 
sum = 45

In Golang there is no foreach loop instead, the for loop can be used as “foreach“. There is a keyword range, you can combine for and range together and have the choice of using the key or value within the loop.

Syntax:  

for <key>, <value> := range <container>{

}

Here, 

  • key and value: It can be any variable you want to choose.
  • container: It can be any variable which is an array, list, map, etc.

Example 1:

Go




package main
 
import "fmt"
 
// Driver function to show the
// use of for and range together
func main() {
 
    // here we used a map of integer to string
    mapp := map[int]string{1: "one", 2: "two", 3: "three"}
 
    // integ act as keys of mapp
    // spell act as the values of
    // mapp which is mapped to integ
 
    for integ, spell := range mapp {
 
        // using integ and spell as
        // key and value of the map
        fmt.Println(integ, " = ", spell)
    }
}


Output:
 

1  =  one
2  =  two
3  =  three

Example 2:

Go




package main
 
import "fmt"
 
// Driver function to show the
// use of for and range together
func main() {
 
    // declaring an array of integers
    arra := []int{1, 2, 3, 4}
 
    // traversing through the array
    for index, itr := range arra {
     
        // the key or value variables
        // used in for syntax
        // depends on the container.
        // If its an array or list,
        // the key refers to the index...
        fmt.Print(index, " : ", itr, "\n")
    }
 
    // if we use only one
    // variable in the for loop,
    // it by default refers to
    // the value in the container.
    for itr := range arra {
 
        fmt.Print(it, " ")
    }
}


Output:
 

0 : 1
1 : 2
2 : 3
3 : 4
1 2 3 4 


Similar Reads

How to iterate over an Array using for loop in Golang?
An array is a data structure of the collection of items of the similar type stored in contiguous locations. For performing operations on arrays, the need arises to iterate through it. A for loop is used to iterate over data structures in programming languages. It can be used here in the following ways: Example 1: // Golang program to iterate over /
2 min read
Switch Case with Break in For Loop in Golang
A switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value, also called the case of the expression. There can be various switch-case statements within a switch. Each case is followed by the value to be compared to. When the variable being switched on is e
3 min read
How to use Array Reverse Sort Functions for Integer and Strings in Golang?
Go language provides inbuilt support implementation of basic constants and run-time reflection to operate sort package. Golang is the ability for functions to run independently of each other. With the help of this function we can easily sort integer and string by importing "sort" package. Basically, this will sort the Integer and Strings in Reverse
1 min read
How to use strconv.QuoteRune() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a QuoteRune() function which is used to find a single-quoted Go string literal representing rune and the returned string uses Go escape sequences (\t, \n, \xFF, \u0100) to control characters
2 min read
How to use strconv.Quote() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a Quote() function which is used to find a double-quoted Go string literal representing str and the returned string uses Go escape sequences (\t, \n, \xFF, \u0100) to control characters and n
2 min read
How to use strconv.QuoteRuneToGraphic() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a QuoteRuneToGraphic() function which is used to find a single-quoted Go character literal representing the rune. If the rune is not a Unicode graphic character as defined by IsGraphic, then
2 min read
How to use strconv.FormatBool() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a FormatBool() function which is used to return true or false according to the value of x. To access FormatBool() function you need to import strconv Package in your program with the help of
2 min read
How to use strconv.CanBackquote() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a CanBackquote() function which is used to check whether the string str can be represented unchanged as a single-line backquoted string without control characters other than a tab or not. To
2 min read
How to use strconv.FormatUint() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a FormatUint() function which is used to return the string representation of x in the given base, i.e., 2 <= base <= 36. Here, the result uses the lower-case letters 'a' to 'z' for digi
2 min read
How to use strconv.IsGraphic() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an IsGraphic() function which is used to check whether the rune is defined as a Graphic by Unicode or not. Such type of characters includes letters, marks, numbers, punctuation, symbols, and
2 min read
How to use strconv.IsPrint() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an IsPrint() function which is used to check whether the rune is defined as printable by Go or not with the same definition as unicode.IsPrint of letters, numbers, punctuation, symbols, and A
2 min read
How to use strconv.Itoa() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an Itoa() function which is equivalent to FormatInt(int64(x), 10). Or in other words, Itoa() function returns the string representation of x when the base is 10. To access Itoa() function you
2 min read
How to use strconv.QuoteToGraphic() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a QuoteToGraphic() function which is used to find a double-quoted Go string literal representing str and the returned string leaves Unicode graphic characters defined by the IsGraphic, unchan
2 min read
How to use strconv.QuoteRuneToASCII() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a QuoteRuneToASCII() function which is used to find a single-quoted Go string literal representing rune and the returned string uses Go escape sequences (\t, \n, \xFF, \u0100) to non-ASCII ch
2 min read
How to use strconv.QuoteToASCII() Function in Golang?
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a QuoteToASCII() function which is used to find a double-quoted Go string literal representing str and the returned string uses Go escape sequences (\t, \n, \xFF, \u0100) to non-ASCII charact
2 min read
How to use Field Tags in the Definition of Struct Type in Golang?
Golang provide structures for the definition of a custom datatype. The concept of structure in Go is similar to the structure in C/C++. Example: type Person struct { Name string Aadhaar int Street string HouseNo int } Structures in Golang can be written to files like JSON for storing data on a hard drive or for sending over the network. JSON is a l
2 min read
How to use Ellipsis (...) in Golang?
The three dots (...) in Golang is termed as Ellipsis in Golang which is used in the variadic function. The function that called with the varying number of arguments is known as variadic function. Or in other words, a user is allowed to pass zero or more arguments in the variadic function. fmt.Printf is the example of the variadic function, it requi
2 min read
Golang Program to Use Field Tags in the Definition of Struct Type
Structure in Golang is used to store different types of data in one place. 'struct' itself is a user-defined data type. The syntax of 'struct' in Golang is as follow: Syntax: type var_name struct { var1 data_type var2 data_type } Structure in Golang is written to files like JSON. It is a data storage format. Golang provides packages in the standard
2 min read
Getting the current date and time with timestamp in local and other timezones in Golang
We can get the current date and time with a timestamp in local with the help of Location() function and other timezones in Golang with the help of LoadLocation() function. The LoadLocation() takes a string(city name) as parameter and returns the place. .location() takes no parameter and return location .time.now() returns current date and time with
2 min read
Difference between var keyword and short declaration operator in Golang
A variable is a storage location or place holder used for holding the value. It allows us to manipulate and retrieve the stored information. There are two ways to declare the variables in Golan which are as follows: var varName type = valuevarName := valueDifference between var keyword and short declaration operatorvar keywordshort declaration oper
4 min read
Golang | Deadlock and Default Case in Select Statement
In Go language, the select statement is just like a switch statement, but in the select statement, the case statement refers to communication, i.e. sent or receive operation on the channel. Syntax: select{ case SendOrReceive1: // Statement case SendOrReceive2: // Statement case SendOrReceive3: // Statement ....... default: // Statement In this arti
3 min read
How to Rename and Move a File in Golang?
In the Go language, you are allowed to rename and move the existing file to a new path with the help of the Rename() method. This method is used to rename and move a file from the old path to the new path. If the given new path already exists and it is not in a directory, then this method will replace it. But OS-specific restrictions may apply when
2 min read
How to Remove All Directories and Files in Golang?
In Go language, you are allowed to remove all the directories and files from a directory or folder with the help of RemoveAll() function. This function removes all the directories and files from the path you will pass to this function. It will remove everything from the specified path, but returns the first error it encounters. If the specified pat
2 min read
How to Find the Sin and Cos Value of a Number in Golang?
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find the value of sin and cos of the specified number with the help of Sincos() function provided by the math package. So, you need to add a math package in your program with the help of
2 min read
How to find the capacity of Channel, Pointer and Slice in Golang?
Go language, capacity defines the maximum number of elements that a particular can hold. Here the task is to find the capacity of Channel, Pointer, and Slice in Golang, we can use the cap() function. Syntax: func cap(l Type) int Here, the type of l is a pointer. Let us discuss this concept with the help of the examples: Example 1: In this example,
2 min read
How to Create and Print Multi Dimensional Slice in Golang?
Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array. Internally, slice and an array are connected with each
2 min read
Calculating total number of Hours, Days, Minutes and Seconds between two dates in Golang
To get the number of days between two dates, we can calculate the number of days from the beginning 0/0/0000 to the first date and the second date and compute their difference. Examples: Input: 2020-04-27 23:35:00, 2018-5-12 12:43:23 Output: 716 days, 10 hours, 51 minutes, 37 seconds Input: 2014-02-25 05:50:20, 2003-12-13 21:42:12 Output: 3726 days
3 min read
How to declare and access pointer variable in Golang?
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like
3 min read
How to find the Length of Channel, Pointer, Slice, String and Map in Golang?
In Golang, len function is used to find the length of a channel, pointer, slice, string, and map. Channel: In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. // Go program to illustrate // how to find the length a channel package main import "fmt" func m
2 min read
How to Get First and Last Element of Slice in Golang?
Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is r
2 min read
Article Tags :
three90RightbarBannerImg