How to exit a go program honoring deferred calls?

前端 未结 4 386
执笔经年
执笔经年 2021-01-30 04:10

I need to use defer to free allocations manually created using C library, but I also need to os.Exit with non 0 status at some point. The

4条回答
  •  难免孤独
    2021-01-30 04:28

    For posterity, for me this was a more elegant solution:

    func main() { 
        retcode := 0
        defer func() { os.Exit(retcode) }()
        defer defer1()
        defer defer2()
    
        [...]
    
        if err != nil {
            retcode = 1
            return
        }
    }
    

提交回复
热议问题