过去的风格指南非常广泛,但谷歌最近发布了他们的 代码审查意见 文档,这几乎就是我们应遵守的公约。因此,我们使用它。

实际上我们把它推进了一点:

  • 避免命名返回参数,除非他们能明确和显着地提高透明度。

  • 避免用 make 和 new,除非他们是必要的(new(int),或 make(Chan int)),或者我们能提前知道要分配的东西的尺寸( make(map[int]string,n),或 make([]int,0,256))。

  • 使用 struct{} 作为标记值,而不是布尔或接口{}。例如,集合是 map[string]struct{};信道是 chan struct{}。它明确标明了信息的明确缺乏。

打断长行的参数也很好。那更象是Java的风格:

// 不要这样。func process(dst io.Writer, readTimeout,    writeTimeout time.Duration, allowInvalid bool,        max int, src <-chan util.Job) {    // ...}

这样会更好:

func process(    dst io.Writer,    readTimeout, writeTimeout time.Duration,    allowInvalid bool,    max int,    src <-chan util.Job,) {    // ...}

当构造对象时也同样分为多行:

f := foo.New(foo.Config{
    Site: "zombo.com",
    Out:  os.Stdout,
    Dest: conference.KeyPair{
        Key:   "gophercon",        Value: 2014,    },})

另外,当分配新的对象时,在初始化部分传递成员值(如上面)比下面这样过后设置要好。

// 不要这样。f := &Foo{} // or, even worse: new(Foo)f.Site = "zombo.com"f.Out = os.Stdoutf.Dest.Key = "gophercon"f.Dest.Value = 2014