How to exit a go program honoring deferred calls?

前端 未结 4 420
执笔经年
执笔经年 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:29

    Just move your program down a level and return your exit code:

    package main
    
    import "fmt"
    import "os"
    
    func doTheStuff() int {
        defer fmt.Println("!")
    
        return 3
    }
    
    func main() {
        os.Exit(doTheStuff())
    }
    

提交回复
热议问题