💻 Tech
For loop in Go can use value or pointer semantics.
Pointer semantics means a piece of code uses references of the original data. This means any manipulation to the references results to changing the original data. In the first for loop, the loop operates on the original data, causing the element in index 1 to be changed.
On the other hand, the second for loop uses its own copy of the original data that’s why when the element in index 1 is changed, it doesn’t affect the copies used by the loop. This is because range
uses the copied data. In addition, v
is a copy of a copy of data. However, fruits[1] = "Strawberry"
did really change the original data. The value semantics here is that the values being iterated are copies of the original array.
// Uses pointer semantic form of the for range
fruits := [4]string{"Apples", "Bananas", "Cherries", "Durian"}
fmt.Printf("Before [%s]: ", fruits[1])
for i := range fruits {
fruits[1] = "Strawberry"
if i == 1 {
fmt.Printf("After[%s]\n", fruits[1])
}
}
// Uses value semantic form of the for range.
fruits = [4]string{"Apples", "Bananas", "Cherries", "Durian"}
fmt.Printf("Before [%s]: ", fruits[1])
for i, v := range fruits {
fruits[1] = "Strawberry"
if i == 1 {
fmt.Printf("v[%s]\n", v)
}
}
Before [Bananas]: After[Strawberry]
Before [Bananas]: v[Bananas]