Go 编码规范 | 青训营笔记

110 阅读2分钟

这是我参与「第三届青训营 - 后端场」笔记创作活动的的第 1 篇笔记。

简介

编写 Go 语言代码中,代码不是随便编写命名的,为了使代码具有可读性以及可维护性,我们在编码时要遵循一些编码规范。Go 语言有特别的编码规范,为了使得代码具有简单性、可读性、生产力,我们需要编码规范来约束我们的代码,使得其简单明了,能够让所有人都明白你写的是什么。

代码格式

  • 使用 gofmt 自动格式化代码

gofmt 是官方的一个 cli 程序,可以使得所有的 Go 代码与官方推荐格式保持一致。

注释

注释是编码规范中很重要的组成部分。一个程序必须要有注释才能具有可读性以及可维护性。注释的编写也不是随便写写的,注释应该提供代码未表达出的上下文信息。注释有以下规范:

  • 解释代码功能 (解释公共符号)

每个公共的符号 (变量、常量、函数、结构) 需要添加注释

// Open opens the named file for reading. If successful, methods on 
// the returned file can be used for reading; the associated file 
// descriptor has mode O_RDONLY. 
// If there is an error, it will be of type *PathError. 
func Open(name string) (*File, error) { 
    return OpenFile(name, O_RDONLY, 0) 
} 
  • 解释代码原理
// Add the Referer header from the most recent 
// request URL to the new one, if it's not https->http: 
if ref := refererForURL(reqs[len(reqs)-1].URL, req.URL); ref != "" { 
    req.Header.Set("Referer", ref) 
} 
  • 解释代码实现
if ireq.GetBody == nil && ireq.outgoingLength() != 0 { 
    // We had a request body, and 307/308 require 
    // re-sending it, but GetBody is not defined. So just 
    // return this response to the user instead of an 
    // error, like we did in Go 1.7 and earlier. 
    shouldRedirect = false 
} 

命名规范

variable

  • 简洁

  • 缩略词大写,不需导出的首字母小写:

// 缩略词大写
var MyApple int
type People struct {
}

// 不需导出的首字母小写
var myPet int
type dog struct {
}
  • 要能轻松辨识出其含义

function

  • 简洁

  • 不携带包名上下文信息,因为包名与函数名成对出现

package time
func Now() {}

time.Now()

package

  • 简洁

  • 由小写字母组成

  • 不与标准库同名

控制流程

  • 避免嵌套

  • 去除冗余的 else

  • 尽量保持少的缩进

错误和异常

  • 优先使用 errors.New 表示错误

  • panic 不直接使用在业务代码中

  • recover 只能在 defer 函数中使用,只在本 goroutine 中生效