Pranava S Balugari
Posted on June 19, 2020
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]
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]
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]
💖 💪 🙅 🚩
Pranava S Balugari
Posted on June 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
google Tough Task? Discover How Google’s AI Can Help You Understand Your Algorithm and Codes Faster.
November 10, 2024