[Go-002] 标识符与关键字

44 阅读1分钟

1 标识符与命名规范

在编程语言中,标识符时程序员定义的具有特殊意义的词,比如变量名、常量名、函数名等。

命名规范:

  • Go 推荐使用驼峰式命名,例如 heapSort
  • 大小写敏感,例如 heapSort 与 HeapSort 不同
  • 由字母、数字、下划线组成,并且只能以字母和_开头,例如abc, _, a123, 123

2 关键字与保留字

关键字和保留字都不建议用作变量名。

关键字,即编程语言中预先定义好的具有特殊含义的标识符,有助于简化编译过程中的代码解析。Go 中有 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

此外,Go 中还有 30 多个保留字,比如inttrue等,主要对应内建的常量、类型和函数这些内部预定义的名字。它们并不是关键字,可以重新使用,但不推荐这样用。

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