25. Defer
Wait Until I am done!
Defer Statement
defer
is special keyword in Go to schedule some action until function returns. Defer is mostly used in cleanup task that should be done when returning from a function. Defer find its use similar to what finally does in some programming languages. Semantic for defer is
defer some_action
main.go
Here, call to print cleanup is scheduled to be executed when function returns. Hello, There is printed first and then Performing cleanup.
Panic scenarios
The benefit of using defer
keyword is that Go guarantees it will be carried out even if there is panic.
main.go
In this case, defer will still print Performing cleanup.
Blog Posts
Last updated