Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

监控团队Golang实践 #19

Open
jacky15 opened this issue Sep 15, 2022 · 3 comments
Open

监控团队Golang实践 #19

jacky15 opened this issue Sep 15, 2022 · 3 comments
Labels

Comments

@jacky15
Copy link
Contributor

jacky15 commented Sep 15, 2022

监控团队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.
}

@dellkeji
Copy link

dellkeji commented Sep 15, 2022

// go 会返回元素对应数据类型的零值,取值操作总有值返回,不能通过取出来的值来判断 key 是不是在 map 中

// error
x := map[string]string{"demo1": "1", "demo2": "2"}
if v := x["demo3"]; v == "" {
  fmt.Println("demo3 is not exist")
}


// right
x := map[string]string{"demo1": "1", "demo2": "2"}
if _, ok := x["demo3"]; !ok {
    fmt.Println("demo3 is not exist")
}

@shamcleren
Copy link

shamcleren commented Sep 16, 2022

// 防止为空的时候 panic

var (
  a  interface{}
  b  int
  ok bool
)

// BAD
b = a.(int)

// GOOD
b, ok = a.(int)

@dellkeji
Copy link

// 定义常量, 区分某些类型、标识等

// BAD
const (
   Red = 0
   Gray  = 1
)

// GOOD
const (
   Red = iota
   Gray 
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants