I have written pointer receiver method with struct A
and created two functions
- expect
A
type slice as parameter and - expect
map[int]A
type Map as parameter.
Both iterate through the values and called pinter receiver method of A. But when it called in map there is a compile error mentioned in below. Both slice element value and map value is main.A
./main.go:28:8: cannot call pointer method on aa[k]
./main.go:28:8: cannot take the address of aa[k]
Code with compilation error is commented and code is below.
package main
type A struct {
I int
}
func (a *A) Add(i int) {
a.I += i
}
func main() {
aa2 := []A{{I:5}}
testSlice(aa2, 10)
//aa1 := map[int]A{
// 5: {I:5},
//}
//testMap(aa1, 10)
}
func testSlice(aa []A, i int) {
for k := range aa {
aa[k].Add(i)
}
}
//func testMap(aa map[int]A, i int) {
// for k := range aa {
// aa[k].Add(i)
// }
//}
Uncommented code is here
Please help me to clear about this, why is this compile error happening?