No, but not impossible
defer
is a keyword designed to execute functions when its parent function returns and starts executing when return statement is reached.
Since defer
in go works like a stack, so calling deferred functions in-order results in a reverse order.
package main
import (
"fmt"
)
func main() {
defer fmt.Println("1")
defer fmt.Println("2")
defer fmt.Println("3")
if num := 2; num == 2 {
defer fmt.Println("4")
return
}
defer fmt.Println("5")
}
// 4
// 3
// 2
// 1
https://play.golang.org/p/jzHG-paytBG
It's best usecases are closing file readers, database transactions, and stacking logs where closing before returning is necessary.
var count
defer println(count)
for { // forever
count++
if count == 100 {
return
}
}
defer pkg.DoCleanup()
something := pkg.DoSomething()
pkg.Add(something.ForCleanup)
pkg.Add(something.ForCleanup)
stream, _ := file.OpenRead("text.txt")
defer stream.Close()
// stream closed
// pkg cleaned
// 100
Workarounds would be like Dennis' answer: https://mcmap.net/q/855585/-c-is-there-39-defer-call-39-like-golang
IDisposable
interface. – MazeDefer
, but by no means I am saying there's noDefer
. Most of the Dispose driven clean up action has to be explicitly called by the used failing which it will lead to a leak – ScaligerTask
s andasync/await
doesn't help here. In your answer you focus on language feature, somehow ignoring what defers are used for. – MazeDefer
does only clean up work, then yes I am wrong, Task, has nothing to do with it, but if its about saving a work to be done later, as understood from the definition, then Task have a role to play out here – Scaliger