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
defer
C
os.Exit
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()) }