I’m within the means of studying go. The under code is an experiment and just about self explanatory. It produces the anticipated consequence.
package deal major
import "fmt"
func major() {
a := []int{1, 2, 3}
z := map[string]func(x int) []int{
"add": func(x int) (b []int) {
b = a
for ok, _ := vary b {
b[k] += x
}
return
},
"sub": func(x int) (b []int) {
b = a
for ok, _ := vary b {
b[k] -= x
}
return
},
}
fmt.Println("add 3:", z["add"](3))
fmt.Println("sub 100:", z["sub"](100))
}
I assume the b = a
might be eradicated whereas conserving the identical conduct, however how?
I wish to apply my understanding of slices, maps, and nameless features, in order that’s why I took this strategy.
NOTE: I wish to iterate over the entire a
slice whether or not it’s 3 gadgets or 100.
EDIT: Stack overflow to the rescue!. It mainly comes right down to the actual fact I didn’t want the reassignment in any respect and I used to be heading in the right direction with utilizing indexes. Right here’s what I ended up with:
package deal major
import "fmt"
func major() {
a := []int{1, 2, 3}
z := map[string]func(x int) []int{
"add": func(x int) []int {
for ok, _ := vary a {
a[k] += x
}
return a
},
"sub": func(x int) []int {
for ok, _ := vary a {
a[k] -= x
}
return a
},
}
fmt.Println("add 3:", z["add"](3))
fmt.Println("sub 100:", z["sub"](100))
}