Skip to content

监控团队Golang实践 #19

@jacky15

Description

@jacky15

监控团队Golang实践

  1. channel空间设定为1或者阻塞
    理由:因为如果改为其他长度的channel,都需要很详细的评估设计,所以建议默认考虑长度为1或阻塞的channel
// BAD
c := make(chan int, 100)

// GOOD
c := make(chan int)
  1. 除for循环以外,不要在代码块初始化中使用:=(如:if代码块)
    理由:如果再代码块中使用了新建变量,容易导致覆盖上层的变量而不会发现,容易引发bug
// BAD 
if _, err := openFile("/path") {
   // do something
}

// GOOD 
var err error
if _, err = openFile("/path") {
   // do something
}
  1. channel接受使用两段式
    理由:可以避免读取已关闭channel导致panic
// GOOD
var (
	ok bool
)
if _, ok = <- ch; !ok {
	// do something when channel is closed.
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions