dpc57092 2012-08-26 04:22
浏览 9

转到:按名称查找功能

I am new to type safe, and can't figure out how to do following

package main

func test(){
    print("In Test")
}

func main(){
    a := "test"
    a()
}
  • 写回答

3条回答 默认 最新

  • doutu3352 2012-08-26 04:25
    关注

    A function can not be resolved from a string. However, you can assign a function to a variable.

    a := test
    a()
    

    You can also put functions (assuming they all have the same signature) into a map:

    var func_map :=  map[string]func() {
        "test": test,
    }
    a := func_map["test"]
    a()
    


    Response to first comment by OP (too long to make another comment):

    1. A function is not a "literal". "Literal" has a separate meaning.
    2. Second, Go's runtime reflection does not have a lookup table mapping strings to functions. Even if it did, functions are not linked into the binary unless linked to by other code. Code only called in this method would not be in the binary.
    3. Third, making a mapping manually is not that hard. It provides compile time type safety checks as well as security.
    4. This is not something you should be doing in any language. It is like eval(), you really should not use it because it can be incredibly dangerous and cause unpredictable things to happen.

    They don't all have the same signature

    If they don't all have the same signature, how do you plan to call them? You could use the reflect package, but that is normally an indication that you are doing something wrong.

    This is not a dynamic language and some things can not be done in Go. Although, they are mostly things you should not do in most languages anyways.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计