DEV Community

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

Posted on

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

Top comments (0)