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条)

报告相同问题?

悬赏问题

  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题