Map 在goLang中声明具有函数指针值的映射

Map 在goLang中声明具有函数指针值的映射,map,go,function-pointers,Map,Go,Function Pointers,我想声明一个类似这样的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

我想声明一个类似这样的
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)

}

如何声明函数指针类型(我在示例中调用&InitFunc,因为我不知道如何声明),以便将其用作映射中的值?

与C不同,您实际上不需要指向函数的“指针”,因为在Go中,函数是引用类型,类似于切片、映射和通道。此外,address运算符&生成指向值的指针,但要声明指针类型,请使用*

您似乎希望InitFunc接受单个InitType,并且不返回任何值。在这种情况下,您可以将其声明为:

type InitFunc func(initType)
现在,地图初始化可以简单地如下所示:

m := make(map[initType]InitFunc)
一个完整的例子是():

主程序包
输入“fmt”
类型InitFunc func(initType)
类型initType int
常数(
A initType=iota
B
C
D
MaxInitType
)
func Init1(t initType){
fmt.Println(“用类型“t”调用Init1)
}
var initFuncs=map[initType]InitFunc{
答:第一,,
}
func init(){
对于t:=A;t

在这里,它循环遍历每个initType,并调用相应的函数(如果已定义)。

您只需执行
map[initType]func(initType)
Tnx-在GoLang中,对于什么是引用类型,什么是值类型等仍然有点困惑。这看起来不错。
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")
}