SOLVED: Learning go, how to simmer this down?

I’m in the process of learning go. The below code is an experiment and pretty much self explanatory. It produces the expected result.

package main

import "fmt"

func main() {
	a := []int{1, 2, 3}
	z := map[string]func(x int) []int{
		"add": func(x int) (b []int) {
			b = a
			for k, _ := range b {
				b[k] += x
			}
			return
		},
		"sub": func(x int) (b []int) {
			b = a
			for k, _ := range b {
				b[k] -= x
			}
			return
		},
	}
	fmt.Println("add 3:", z["add"](3))
	fmt.Println("sub 100:", z["sub"](100))
}

I think the b = a can be eliminated while keeping the same behavior, but how?

I want to practice my understanding of slices, maps, and anonymous functions, so that’s why I took this approach.

NOTE: I want to iterate over the whole a slice whether it’s 3 items or 100.

EDIT: Stack overflow to the rescue!. It basically comes down to the fact I didn’t need the reassignment at all and I was on the right track with using indexes. Here’s what I ended up with:

package main

import "fmt"

func main() {
	a := []int{1, 2, 3}
	z := map[string]func(x int) []int{
		"add": func(x int) []int {
			for k, _ := range a {
				a[k] += x
			}
			return a
		},
		"sub": func(x int) []int {
			for k, _ := range a {
				a[k] -= x
			}
			return a
		},
	}
	fmt.Println("add 3:", z["add"](3))
	fmt.Println("sub 100:", z["sub"](100))
}
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.