duanjianlu0506 2014-01-28 21:24
浏览 102
已采纳

在goLang中使用函数指针值声明地图

I'd like to declare a map that would that would look like this, so I could map various init functions to 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)

}

How do I declare the function pointer type (which I called &InitFunc in the example because I don't know how to do it) so I can use it as the value in a Map?

  • 写回答

1条回答 默认 最新

  • duanjiu1894 2014-01-28 21:43
    关注

    Unlike C, you don't actually need a "pointer" to the function, since in Go, functions are reference types, similar to slices, maps, and channels. Further, the address operator, &, produces a pointer to a value, but to declare a pointer type, use *.

    You seem to be wanting your InitFunc to take a single InitType and return no values. In that case, you would declare it as:

    type InitFunc func(initType)
    

    Now, your map initialization can simply look like:

    m := make(map[initType]InitFunc)
    

    A complete example would be (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")
    }
    

    Here, it's looping through each initType, and calling the applicable function, if it is defined.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里