defer (延迟调用)是 Go语言中的一个关键字,一般用于释放资源和连接、关闭文件、释放锁等。
和defer类似的有java的finally和C++的析构函数,这些语句一般是一定会执行的(某些特殊情况后文会提到),不过析构函数析构的是对象,而defer后面一般跟函数或方法。
package counter
import (
"log"
"sync"
)
type Counter struct {
mu *sync.Mutex
Value int
}
func NewCounter(value int) *Counter {
return &Counter{
new(sync.Mutex), 0,
}
}
func (c *Counter) Increment() {
c.mu.Lock()
// defer func
defer func() {
c.mu.Unlock()
log.Printf("mu sync.Mutex Unlocked!")
}()
// safe increment Value
c.Value++
}