Zero Values Are Ready To Use
Rely on Go zero values: declare with var and use immediately, learn where nil maps stay read-only, and give mutexes no explicit initialization.
Code
package main
import (
"fmt"
"sync"
)
// 零值即可用:var 声明后无需初始化表达式
type Counter struct {
mu sync.Mutex // 零值就是已解锁状态,可直接 Lock
n map[string]int
}
func (c *Counter) Add(key string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.n == nil {
c.n = make(map[string]int) // nil map 只读安全;写入前必须 make
}
c.n[key]++
}
func main() {
var c Counter
c.Add("hits")
c.Add("hits")
c.Add("miss")
fmt.Println("hits:", c.n["hits"], "miss:", c.n["miss"])
// 基础类型的零值:未赋值字段保持类型默认值
var (
count int
ratio float64
enabled bool
name string
)
fmt.Println(count, ratio, enabled, name == "")
}How it works
The part worth importing is the functions Add and main — everything else is wiring.
A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
Using it
The main signature reads func (c *Counter) Add(key string)
The demo output is labeled (hits:), so the output doubles as a step-by-step trace of what the file did.
The sequence Add lives in main; running the file triggers it.
Key statements
func (c *Counter) Add(key string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.n == nil {
c.n = make(map[string]int) // nil map 只读安全;写入前必须 make
}
c.n[key]++
}
mu sync.Mutex // 零值就是已解锁状态,可直接 Lock
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Zero Values Are Ready To Use print when run?
- Run it as a complete program — the output lines carry labels such as `hits:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.