Is it possible to defer
to the end of an outer function?
// normal transaction
func dbStuff(){
db.Begin()
...
db.Commit()
}
// normal transaction w/ defer
func dbStuff(){
db.Begin()
defer db.Commit()
...
}
Is this possible?
// can you defer to caller / outer function?
func dbStuff(){
db.Trans()
...
}
// will Commit() when dbStuff() returns
func (db Db) Trans(){
db.Begin()
defer db.Commit() // to caller/outer function
}
According to the specification, it's not possible:
A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.
(emphasis mine)
Update: Apart from that, it would not be a good idea either – one of the strengths of Go is "what you see is what you get". Deferring functions from inner functions to outer functions would create 'invisible' changes in your control flow.