What is the use of defer in Go? The language documentation says it is executed when the surrounding function returns. Why not just put the code at end of given
There are already good answers here. I would like to mention one more use case.
func BillCustomer(c *Customer) error {
c.mutex.Lock()
defer c.mutex.Unlock()
if err := c.Bill(); err != nil {
return err
}
if err := c.Notify(); err != nil {
return err
}
// ... do more stuff ...
return nil
}
The defer in this example ensures that no matter how BillCustomer returns, the mutex will be unlocked immediately prior to BillCustomer returning. This is extremely useful because without defer you would have to remember to unlock the mutex in every place that the function could possibly return.
ref.