Golang 标识符、关键字和命名规范

撰写风格

Golang 中有几项规定,当不匹配以下规定时,编译就会产生错误:

  • 每行程序结束后,不需要写分号
  • 左大括号不能换行放置
  • if 判断和 for 循环,不需要以小括号包裹起来

当前,Go 语言有内置的 go fmt 工具,能够自动整理代码多余的空白、变量名对齐、将对齐空格转换为 Tab ...


命名规范

Golang中,变量、常量、自定义类型、函数及包( package )的命名方式,遵循以下规则:

  • 以字母( 任意 Unicode 字符 )或下划线( _ )开头
  • 后面可以跟任意长度的数字、字母、下划线( _ )
  • 非关键字和保留字
// 关键字 25 个
    break        default      func         interface    select
    case         defer        go           map          struct
    chan         else         goto         package      switch
    const        fallthrough  if           range        type
    continue     for          import       return       var

// 保留字 37 个
    Constants:    true  false  iota  nil

    Types:    int  int8  int16  int32  int64  
              uint  uint8  uint16  uint32  uint64  uintptr
              float32  float64  complex128  complex64
              bool  byte  rune  string  error

    Functions:   make  len  cap  new  append  copy  close  delete
                 complex  real  imag
                 panic  recover