Working with Go


Go uses for for all loops, there is no while or do-while loops.

For Loop

alphas := []string{"abc", "def", "ghi"}

// standard for loop
for i := 0; i < len(alphas); i++ {
    fmt.Printf("%d: %s \n", i, alphas[i])

// counting backwards
for i := len(alphas)-1; i >= 0; i-- {
    fmt.Printf("%d: %s \n", i, alphas[i])

Using Range

Iterating over an array is easier using range function.

for i, val := range alphas {
    fmt.Printf("%d: %s \n", i, val)

If you did not care about the value and only wanted the index

for i := range alphas {

If you did not care about the index and only the value, you need to use the _ character.

for _, val := range alphas {

Use For like While

x := 0
for x < 10 {

Infinite Loop

for {

Hi, I’m Marcus Kazmierczak

Profile Photo I'm an engineer trying to do my small part to make the web a little better. I believe open source can help empower people, and grow our collective knowledge; moving the world forward. I hope this site is a small contribution to that collective.