Vec*_*tor 3 function-pointers map go
我想声明一个map看起来像这样的东西,所以我可以将各种init函数映射到initType:
func makeMap(){
m := make(map[initType]&InitFunc)
//How should the value declaration be set up for this map?
}
type initType int
const(
A initType = iota
B
C
D
)
func init(aInitType initType){
doStuff(aInitType)
}
func init(aInitType initType){
doOtherStuff(aInitType)
}
func init(aInitType initType){
doMoreStuff(aInitType)
}
Run Code Online (Sandbox Code Playgroud)
如何声明函数指针类型(我在示例中调用了&InitFunc,因为我不知道如何操作)所以我可以将它用作Map中的值?
与C不同,您实际上并不需要函数的"指针",因为在Go中,函数是引用类型,类似于切片,贴图和通道.此外,地址运算符&和产生指向值的指针,但要声明指针类型,请使用*.
您似乎希望您的InitFunc采用单个InitType并且不返回任何值.在这种情况下,您将其声明为:
type InitFunc func(initType)
Run Code Online (Sandbox Code Playgroud)
现在,您的地图初始化可能看起来像:
m := make(map[initType]InitFunc)
Run Code Online (Sandbox Code Playgroud)
一个完整的例子是(http://play.golang.org/p/tbOHM3GKeC):
package main
import "fmt"
type InitFunc func(initType)
type initType int
const (
A initType = iota
B
C
D
MaxInitType
)
func Init1(t initType) {
fmt.Println("Init1 called with type", t)
}
var initFuncs = map[initType]InitFunc{
A: Init1,
}
func init() {
for t := A; t < MaxInitType; t++ {
f, ok := initFuncs[t]
if ok {
f(t)
} else {
fmt.Println("No function defined for type", t)
}
}
}
func main() {
fmt.Println("main called")
}
Run Code Online (Sandbox Code Playgroud)
在这里,它循环遍历每个initType,并调用适用的函数(如果已定义).
| 归档时间: |
|
| 查看次数: |
5208 次 |
| 最近记录: |