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.

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

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器