Go For Range

In this tutorial you will learn about the Go For Range and its application with practical example.

Go For Range

In GoLang, for loop with a “range” clause iterates through every element in an array, slice, string, map, or values received on a channel. A range keyword is used to iterate over slices, arrays, strings, maps or channels.

Synatx:-

here, individual keys and values are held in the corresponding variable and key or value can be omitted if one or the other is not needed using ‘_’

Example:-

Output:-

go_for_each_1

 

Go For Range with Strings

For a string, the for loop iterates over each characters’s Unicode code points. The first value is the starting byte index of the rune and the second the rune itself.

Example:-

Output:-

go_for_each_with_strings

Go For Range with Map

In GoLang, range on map iterates over key/value pairs. It can also iterate over just the keys of a map.

Recommended:-  Go String Formatting

Example:-

Output:-

go_for_each_with_map

Go For Range with Channel

For channel, it iterates over values sent on the channel until closed.

Example:-

Output:-

go_for_each_with_channel

In this tutorial we have learn about the Go For Range and its application with practical example. I hope you will like this tutorial.