Discovering Methods in Go Packages
In Go, as you've noticed in your first week, there is no direct mechanism to dynamically iterate through the methods of a package. Unlike languages like Python, Go does not introspect the contents of packages.
This design decision stems from Go's rigorous compilation process, which keeps only functions and variables that are explicitly referenced in the executable. Any unused functions or variables are discarded at compile time. Consequently, iterating over a potentially incomplete set of symbols becomes meaningless and is not implemented.
Alternative Approach
To circumvent this limitation, consider creating an array containing objects of the types you wish to operate on. For example, in your calculator scenario, you could define an array:
var calculators = []*calculator.Calc{&calculator.Add{}, &calculator.Sub{}, &calculator.Mult{}, ...}
You can then iterate through this array, calling the First and Second methods on each calculator.Calc object. While this approach may seem slightly verbose, it allows you to iterate through a complete set of methods known to your program.
The above is the detailed content of How to Iterate Through Methods in Go Packages?. For more information, please follow other related articles on the PHP Chinese website!