Here is my program:
package main
import (
"fmt"
)
type Number struct {
val int
}
func (num * Number) Increment () {
num.val += 1
}
func (num Number) Value() int {
return num.val
}
func main() {
numbers := []Number {
{val: 12},
{val: 7},
{val: 0},
}
for _, each := range numbers {
each.Increment()
fmt.Println(each.Value())
}
for _, each := range numbers {
fmt.Println(each.Value())
}
}
Here is the output:
13
8
1
12
7
0
First question: why does the Increment()
method not update the value in the first for loop? I used pointer as the receiver so that val
can be updated for sure, but why would the second for
loop print out the original values of those Number
s?
Second question: what can be done so that when I iterate over a slice of Number
s and invoke the Increment()
method, all Number
s are correctly incremented?
[Edit] I noticed that if I use index-based for
loop and invoke the Increment()
method, values will be correctly updated. Why?
for i := 0; i < len(numbers); i++ {
numbers[i].Increment()
}