DEV Community

Cover image for GoLang for loop variations
Pranava S Balugari
Pranava S Balugari

Posted on

1 1

GoLang for loop variations

Go has only one looping construct, the for loop. It comes with 2 variations from a usability point of view. Understanding the differences will definitely help in implementing the right one at the right time :).

Table Of Contents

Pointer semantic form

In this one the loop happens on the original continents array.

// Using the Pointer semantic form of for: <- range

package main

import "fmt"

func main() {
 continents := [3]string{'Asia', 'Africa','Australia'}
 fmt.Printf("Before -> [%s] : ", continents[1])

 for i := range continents {
    continents[1] = 'Europe'

    if i == 1 {   
       fmt.Printf("After -> [%s] : ", continents[1])
    }

 }

}

Output:
Before -> [Africa] : After -> [Europe]


Enter fullscreen mode Exit fullscreen mode

Value semantic form

In this one the looping happens on the copy of the original array.

// Using the value semantic form of for: <- range

package main

import "fmt"

func main() {
 continents := [3]string{'Asia', 'Africa','Australia'}
 fmt.Printf("Before -> [%s] : ", continents[1])

 for i, c := range continents {
    continents[1] = 'Europe'

    if i == 1 {   
       fmt.Printf("After -> [%s] : ", c)
    }

 }

}

Output:
Before -> [Africa] : After -> [Africa]


Enter fullscreen mode Exit fullscreen mode

There is one more value semantic form of the for range but with pointer semantic access. DON'T DO THIS.


package main

import "fmt"

func main() {
 continents := [3]string{'Asia', 'Africa','Australia'}
 fmt.Printf("Before -> [%s] : ", continents[1])

 for i, c := range &continents {
    continents[1] = 'Europe'

    if i == 1 {   
       fmt.Printf("After -> [%s] : ", c)
    }

 }

}

Output:
Before -> [Africa] : After -> [Europe]


Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay