var mutex sync.Mutex type Person struct { Age int } persons := make([]Person, 10) for _, p := range persons { mutex.Lock() defer mutex.Unlock() p.Age = 13 }
var mutex sync.Mutex type Person struct { Age int } persons := make([]Person, 10) for _, p := range persons { mutex.Lock()
p.Age = 13 mutex.Unlock() }
如果你确实需要在循环中使用 defer,可以考虑将工作委托给另一个函数:
1 2 3 4 5 6 7 8 9 10 11 12
var mutex sync.Mutex type Person struct { Age int } persons := make([]Person, 10) for _, p := range persons { func() { mutex.Lock() defer mutex.Unlock() p.Age = 13 }() }
2. 往 unbuffered channel 中发送数据
1 2 3 4 5 6 7 8 9 10 11 12 13
func doReq(timeout time.Duration) obj { ch :=make(chan obj) go func() { obj := do() ch <- obj } () select { case result = <- ch : return result case<- time.After(timeout): return nil } }
type OrderedPerson struct { Name string Age int32 Veteran bool }
在频繁使用不合理字段顺序的类型时,会导致额外的内存开销。
不过,我们也不必手动计算和优化结构体内存,可以使用 go tool 提供的 fieldalignment 工具来检测并修复不合理的声明顺序。
fieldalignment 安装:
1 2 3 4
cd $GOPATH git clone [email protected]:golang/tools.git src/golang.org/x/tools src/golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment go install
fieldalignment 使用
1 2 3 4 5 6
➜ fieldalignment . /Users/jiapan/Projects/tantan-live-distribution/app/domain/recommend_service.go:179:30: struct of size 88 could be 80 /Users/jiapan/Projects/tantan-live-distribution/app/domain/voice_recommend_service.go:63:35: struct with 40 pointer bytes could be 24
$ go test -race pkg // to test the package $ go run -race pkg.go // to run the source file $ go build -race // to build the package $ go install -race pkg // to install the package