DEV Community

Cover image for Defer in Golang
Onyedikachi Emmanuel Nnadi
Onyedikachi Emmanuel Nnadi

Posted on

Defer in Golang

Defer means: don't run this now (function) hold onto it, and run it automatically right before the function ends.

It doesn't pause anything. Your code keeps running normally. The deferred line just waits its turn till the very end.

For example: borrowing a library book 📚

You check out a book. The moment you do, you say "I'll return this before I leave the library.

You don't return it immediately, you go read, photocopy pages, chat with a friend...

But no matter how you leave, calmly, in a rush, through a different exit you automatically return the book at the front desk before you're gone.

You said it once, up front. It's guaranteed to happen.

Hope you learnt something from this, drop your thoughts in the comment section, Please like, share and follow for more contents 😊

Top comments (0)