Uber Go 语言编程规范

不必要的else

如果在if的两个分支中都设置了变量,则可以将其替换为单个if。

Bad

1
2
3
4
5
6
var a int
if b {
    a = 100
} else {
    a = 10
}

Good

1
2
3
4
a := 10
if b {
    a = 100
}

减少嵌套

代码应通过尽可能先处理错误情况/特殊情况并尽早返回或继续循环来减少嵌套。减少嵌套多个级别的代码的代码量。

Bad

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
for _, v := range data {
  if v.F1 == 1 {
    v = process(v)
    if err := v.Call(); err == nil {
      v.Send()
    } else {
      return err
    }
  } else {
    log.Printf("Invalid v: %v", v)
  }
}

Good

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
for _, v := range data {
  if v.F1 != 1 {
    log.Printf("Invalid v: %v", v)
    continue
  }

  v = process(v)
  if err := v.Call(); err != nil {
    return err
  }
  v.Send()
}

Start Enums at One

The standard way of introducing enumerations in Go is to declare a custom type and a const group with iota.
Since variables have a 0 default value, you should usually start your enums on a non-zero value.

Bad

1
2
3
4
5
6
7
8
9
type Operation int

const (
  Add Operation = iota
  Subtract
  Multiply
)

// Add=0, Subtract=1, Multiply=2

Good

1
2
3
4
5
6
7
8
9
type Operation int

const (
  Add Operation = iota + 1
  Subtract
  Multiply
)

// Add=1, Subtract=2, Multiply=3

Defer to Clean Up

Use defer to clean up resources such as files and locks.

Bad

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
p.Lock()
if p.count < 10 {
  p.Unlock()
  return p.count
}

p.count++
newCount := p.count
p.Unlock()

return newCount

// easy to miss unlocks due to multiple returns

Good

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
p.Lock()
defer p.Unlock()

if p.count < 10 {
  return p.count
}

p.count++
return p.count

// more readable

优先使用strconv而不是fmt

将原语转换为字符串或从字符串转换时,strconv速度比fmt快。

Bad

1
2
3
4
5
for i := 0; i < b.N; i++ {
  s := fmt.Sprint(rand.Int())
}

BenchmarkFmtSprint-4    143 ns/op    2 allocs/op

Good

1
2
3
4
5
for i := 0; i < b.N; i++ {
  s := strconv.Itoa(rand.Int())
}

BenchmarkStrconv-4    64.2 ns/op    1 allocs/op

相似的声明放在一组

Go语言支持将相似的声明放在一个组内

Bad

1
2
import "a"
import "b"

Good

1
2
3
4
import (
  "a"
  "b"
)

这同样适用于常量、变量和类型声明

Bad

1
2
3
4
5
6
7
8
const a = 1
const b = 2

var a = 1
var b = 2

type Area float64
type Volume float64

Good

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const (
  a = 1
  b = 2
)

var (
  a = 1
  b = 2
)

type (
  Area float64
  Volume float64
)

仅将相关的声明放在一组。不要将不相关的声明放在一组。

Bad

1
2
3
4
5
6
7
8
type Operation int

const (
  Add Operation = iota + 1
  Subtract
  Multiply
  ENV_VAR = "MY_ENV"
)

Good

1
2
3
4
5
6
7
8
9
type Operation int

const (
  Add Operation = iota + 1
  Subtract
  Multiply
)

const ENV_VAR = "MY_ENV"

分组使用的位置没有限制,例如:你可以在函数内部使用它们

Bad

1
2
3
4
5
6
7
func f() string {
  var red = color.New(0xff0000)
  var green = color.New(0x00ff00)
  var blue = color.New(0x0000ff)

  ...
}

Good

1
2
3
4
5
6
7
8
9
func f() string {
  var (
    red   = color.New(0xff0000)
    green = color.New(0x00ff00)
    blue  = color.New(0x0000ff)
  )

  ...
}

import组内的包导入顺序

There should be two import groups:
  Standard library
  Everything else
This is the grouping applied by goimports by default.

Bad

1
2
3
4
5
6
import (
  "fmt"
  "os"
  "go.uber.org/atomic"
  "golang.org/x/sync/errgroup"
)

Good

1
2
3
4
5
6
7
import (
  "fmt"
  "os"

  "go.uber.org/atomic"
  "golang.org/x/sync/errgroup"
)

函数分组与顺序

  • 函数应按粗略的调用顺序排序。
  • 同一文件中的函数应按接收者分组。

因此,导出的函数应先出现在文件中,放在struct、const和var定义的后面。

在定义类型之后,但在接收者的其余方法之前,可能会出现一个newXYZ()/ NewXYZ()。

由于函数是按接收者分组的,因此普通工具函数应在文件末尾出现。

Bad

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func (s *something) Cost() {
  return calcCost(s.weights)
}

type something struct{ ... }

func calcCost(n int[]) int {...}

func (s *something) Stop() {...}

func newSomething() *something {
    return &something{}
}

Good

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type something struct{ ... }

func newSomething() *something {
    return &something{}
}

func (s *something) Cost() {
  return calcCost(s.weights)
}

func (s *something) Stop() {...}

func calcCost(n int[]) int {...}

顶层变量声明

在顶层,使用标准var关键字。请勿指定类型,除非它与表达式的类型不同。

Bad

1
2
3
var _s string = F()

func F() string { return "A" }

Good

1
2
3
4
var _s = F()
// 由于F已经明确了返回一个字符串类型,因此我们没有必要显式指定_s的类型

func F() string { return "A" }

Prefix Unexported Globals with _

Prefix unexported top-level vars and consts with _ to make it clear when they are used that they are global symbols.

Exception: Unexported error values, which should be prefixed with err.

Rationale: Top-level variables and constants have a package scope. Using a generic name makes it easy to accidentally use the wrong value in a different file.

Bad

1
2
3
4
const (
  defaultPort = 8080
  defaultUser = "user"
)

Good

1
2
3
4
const (
  _defaultPort = 8080
  _defaultUser = "user"
)

Embedding in Structs

Embedded types (such as mutexes) should be at the top of the field list of a struct, and there must be an empty line separating embedded fields from regular fields.

Bad

1
2
3
4
type Client struct {
  version int
  http.Client
}

Good

1
2
3
4
5
type Client struct {
  http.Client

  version int
}

使用字段名初始化结构体

初始化结构体时,几乎始终应该指定字段名称。现在由go vet强制执行。

Bad

1
k := User{"John", "Doe", true}

Good

1
2
3
4
5
k := User{
    FirstName: "John",
    LastName: "Doe",
    Admin: true,
}

例外:如果有3个或更少的字段,则可以在测试表中省略字段名称。

1
2
3
4
5
6
7
8
tests := []struct{
}{
  op Operation
  want string
}{
  {Add, "add"},
  {Subtract, "subtract"},
}

本地变量声明

如果将变量明确设置为某个值,则应使用短变量声明形式(:=)。

Bad

1
var s = "foo"

Good

1
s := "foo"

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

Bad

1
2
3
4
5
6
7
8
func f(list []int) {
  filtered := []int{}
  for _, v := range list {
    if v > 10 {
      filtered = append(filtered, v)
    }
  }
}

Good

1
2
3
4
5
6
7
8
func f(list []int) {
  var filtered []int
  for _, v := range list {
    if v > 10 {
      filtered = append(filtered, v)
    }
  }
}

nil是一个有效的slice

nil是一个有效的长度为0的slice,这意味着:
  • 您不应明确返回长度为零的切片。返回nil 来代替。

Bad

1
2
3
if x == "" {
  return []int{}
}

Good

1
2
3
if x == "" {
  return nil
}
  • 要检查切片是否为空,请始终使用len(s) == 0。不要检查 nil。

Bad

1
2
3
func isEmpty(s []string) bool {
  return s == nil
}

Good

1
2
3
func isEmpty(s []string) bool {
  return len(s) == 0
}
  • 零值切片可立即使用,无需调用make创建。

Bad

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
nums := []int{}
// or, nums := make([]int)

if add1 {
  nums = append(nums, 1)
}

if add2 {
  nums = append(nums, 2)
}

Good

1
2
3
4
5
6
7
8
9
var nums []int

if add1 {
  nums = append(nums, 1)
}

if add2 {
  nums = append(nums, 2)
}

缩小变量作用域

如果有可能,尽量缩小变量作用范围。除非它与减少嵌套的规则冲突。

Bad

1
2
3
4
err := ioutil.WriteFile(name, data, 0644)
if err != nil {
    return err
}

Good

1
2
3
if err := ioutil.WriteFile(name, data, 0644); err != nil {
    return err
}

如果需要在if之外使用函数调用的结果,则不应尝试缩小范围。

Bad

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
if data, err := ioutil.ReadFile(name); err == nil {
  err = cfg.Decode(data)
  if err != nil {
    return err
  }

  fmt.Println(cfg)
  return nil
} else {
  return err
}

Good

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
data, err := ioutil.ReadFile(name)
if err != nil {
   return err
}

if err := cfg.Decode(data); err != nil {
  return err
}

fmt.Println(cfg)
return nil

避免裸参数

函数调用中的裸参数可能会损害可读性。当参数名称的含义不明显时,请为参数添加C样式注释(/* … */)。

Bad

1
2
3
// func printInfo(name string, isLocal, done bool)

printInfo("foo", true, true)

Good

1
2
3
// func printInfo(name string, isLocal, done bool)

printInfo("foo", true /* isLocal */, true /* done */)

初始化结构体引用

在初始化结构引用时,请使用&T{}代替new(T),以使其与结构体初始化一致。

Bad

1
2
3
4
5
sval := T{Name: "foo"}

// 不一致
sptr := new(T)
sptr.Name = "bar"

Good

1
2
3
sval := T{Name: "foo"}

sptr := &T{Name: "bar"}

格式化字符串放在Printf外部

如果你为Printf-style函数声明格式字符串,请将格式化字符串放在外面,并将其设置为const常量。

Bad

1
2
msg := "unexpected values %v, %v\n"
fmt.Printf(msg, 1, 2)

Good

1
2
const msg = "unexpected values %v, %v\n"
fmt.Printf(msg, 1, 2)

Initializing Maps

if the map holds a fixed list of elements, use map literals to initialize the map.

Bad

1
2
3
4
m := make(map[T1]T2, 3)
m[k1] = v1
m[k2] = v2
m[k3] = v3

Good

1
2
3
4
5
m := map[T1]T2{
  k1: v1,
  k2: v2,
  k3: v3,
}

测试表

在核心测试逻辑重复时,将表驱动测试与子测试一起使用,以避免重复代码。

Bad

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// func TestSplitHostPort(t *testing.T)

host, port, err := net.SplitHostPort("192.0.2.0:8000")
require.NoError(t, err)
assert.Equal(t, "192.0.2.0", host)
assert.Equal(t, "8000", port)

host, port, err = net.SplitHostPort("192.0.2.0:http")
require.NoError(t, err)
assert.Equal(t, "192.0.2.0", host)
assert.Equal(t, "http", port)

host, port, err = net.SplitHostPort(":8000")
require.NoError(t, err)
assert.Equal(t, "", host)
assert.Equal(t, "8000", port)

host, port, err = net.SplitHostPort("1:8")
require.NoError(t, err)
assert.Equal(t, "1", host)
assert.Equal(t, "8", port)

Good

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// func TestSplitHostPort(t *testing.T)

tests := []struct{
  give     string
  wantHost string
  wantPort string
}{
  {
    give:     "192.0.2.0:8000",
    wantHost: "192.0.2.0",
    wantPort: "8000",
  },
  {
    give:     "192.0.2.0:http",
    wantHost: "192.0.2.0",
    wantPort: "http",
  },
  {
    give:     ":8000",
    wantHost: "",
    wantPort: "8000",
  },
  {
    give:     "1:8",
    wantHost: "1",
    wantPort: "8",
  },
}

for _, tt := range tests {
  t.Run(tt.give, func(t *testing.T) {
    host, port, err := net.SplitHostPort(tt.give)
    require.NoError(t, err)
    assert.Equal(t, tt.wantHost, host)
    assert.Equal(t, tt.wantPort, port)
  })
}

参考