Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Defer to act on caller / outer function?

Tags:

go

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
}
like image 342
Derek Avatar asked Feb 14 '23 20:02

Derek


1 Answers

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.

like image 195
publysher Avatar answered Mar 08 '23 12:03

publysher