Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Unlike other languages, Go has one looping construct — the for loop. However, the for loop can handle all of your looping needs. I will show you examples of how to use the for loop to count from 1 to 10 and how to loop over an array/slice in different ways.
Count From 1 to 10 Using The Standard For Loop
In this example, we use the standard for loop that is available in most programming languages. This code loops from 1 to 10 and prints out the values from 1 to 10.
This will print the following:
12345678910
Count From 1 to 10 Using For Loop Like A While Loop
This will print the following:
12345678910
Looping Over An Slice Or an Array
In this example, we create a slice with 10 items. This code loops over the slice and prints the value at the index.
This will print the following:
90108020803070406050
Looping Over a Slice or an Array Using Range
In this example, the code loops through all the elements in an array or slice and prints out their value.
This will print the following:
90108020803070406050
Looping Over a Slice or Array Using Range With Index
In this example, the code loops through all the elements in the array or slice like in the example above. However, the code prints both the index of the element and the element value.
This will print the following:
index: 0 value: 90index: 1 value: 10index: 2 value: 80index: 3 value: 20index: 4 value: 80index: 5 value: 30index: 6 value: 70index: 7 value: 40index: 8 value: 60index: 9 value: 50
Conclusion
So those are just a few examples of how to use a for loop to count from 1 to 10 and loop for an slice or array.
Go For Loops was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.