This is my first week with Go, so please forgive the ignorance ;). I come in peace from Python. I am building a simple calculator with Addition and Subtraction currently.
My addition.go
file looks like this:
package calculator
type Add struct{}
func (h Add) First(x int) int {
x += 5
return x
}
func (h Add) Second(x int) int {
x += 10
return x
}
The layout of my subtraction.go
file looks very similar to addition.go
and future features like multiplication.go
and division.go
will look similar. To run these I have:
package main
import (
"fmt"
"github.com/mytester/calculator"
)
type Calc interface {
First(x int) int
Second(x int) int
}
func main() {
x := 10
var i Calc
a := &calculator.Add{}
i = a
i.First(x)
fmt.Println(x)
fmt.Println(i.First(x))
fmt.Println(i.Second(x))
fmt.Println("Next method...")
b := &calculator.Sub{}
i = b
fmt.Println(x)
fmt.Println(i.First(x))
fmt.Println(i.Second(x))
// iterate through the rest of my calculator methods
}
This seems very verbose, especially as I add more and more features like multiplication, etc. Is there a way to find all the methods of my calculator & then iterate over all of them? I've looked through the reflect
documentation but there doesn't seem to be a way to get this. The order in which they are run doesn't matter....eg subtraction can run before addition.
Go does not provide the feature you want. There is no mechanism to introspect the contents of packages. The reason for this is that the compiler keeps only functions and variable in the executable that are referenced somewhere. If you never explicitly use a function, it won't be in the executable. Iterating over a possibly incomplete set of symbols is pointless and is therefore not implemented.
You could make an array containing objects of the types you want to operate on and iterate on that if that solves your problem.