Use of defer in Go

前端 未结 6 1584
谎友^
谎友^ 2020-12-13 12:45

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

6条回答
  •  天命终不由人
    2020-12-13 13:05

    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.

提交回复
热议问题