代码
package calc
import "fmt"
type Number struct {
Val int
}
const (
testConst1 = iota
testConst2
testConst3
)
// 定义要使用的方法
type funcTest func(n int) *Number
// 方法容器
var testModules = make(map[int]funcTest)
// 初始化 绑定具体的方法
func init() {
testModules[testConst1] = calc1
testModules[testConst2] = calc1
testModules[testConst3] = calc1
}
// 具体实现方法
func calc1(num int) *Number {
n := &Number{}
n.Val *= num
return n
}
// 可以利用容器 依次循环返回值
func Calc() {
// cost 为容器键 fun 为容器具体内容(这里为函数)
for cost, fun := range testModules {
fmt.Println("cost is", cost)
funRes := fun(cost)
fmt.Println("funRes is", funRes)
}
}