本地变量声明

如果在变量初始化时赋值,则应使用短变量声明形式:=

//bad uasge
var s = "foo"
//good usage
s := "foo"

但是,在某些情况下,var 使用关键字时默认值会更清晰。例如,声明空切片。

//bad uasge
func f(list []int) {
  filtered := []int{}
  for _, v := range list {
    if v > 10 {
      filtered = append(filtered, v)
    }
  }
}
//good usage
func f(list []int) {
  var filtered []int
  for _, v := range list {
    if v > 10 {
      filtered = append(filtered, v)
    }
  }
}

Last updated

Was this helpful?