doupin2013 2018-12-01 21:23
浏览 79
已采纳

Golang的自调用功能

Could not easily find info on how to create a self-invoking func in Golang.

My end-goal is to export a map from a file, something like this:

type Foo struct {}
type Bar struct {}

var TypeMap map[interface{}]string;

func selfInvoking(){

  TypeMap = map[interface{}]string{
    Foo: "foo",
    Bar: "bar"
   }
}()

how can I go about exporting a populated map like this from a file in Go? It's basically for one-time configuration.

Using the pattern above, I will get

"unused variable TypeMap".

  • 写回答

2条回答 默认 最新

  • douhe2305 2018-12-01 22:29
    关注

    There are 3 ways to execute initialization code in GO:

    In your case you can use last two.

    Variable:

    var TypeMap = map[interface{}]string{
        Foo{}: "foo",
        Bar{}: "bar",
       }
    

    The init function:

    var TypeMap map[interface{}]string
    
    func init(){
      TypeMap = map[interface{}]string{
        Foo: "foo",
        Bar: "bar",
       }
    }
    

    In any case be careful with initializers and do not use them for any complex or io code. Initializer are not very good for unit testing and errors handling/logging.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?