GO语言--变量、常量

变量命名

1.变量命令

以数字、字母、_组成,并且只能以字母、_ 开头。例如:abc、_abc、ad123

建议使用小驼峰命名。 例如:helloWord

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语言中还有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

3.变量类型

常见的变量类型分为:整型、浮点型、布尔型

4.变量声明

var a int = 123
var a = 123
a := 123
_ 为匿名变量,不占用内存空间

注意事项:

  1. 函数外的每个语句都必须以关键字开始(var、const、func等)
  2. :=不能使用在函数外。
  3. _多用于占位,表示忽略值。

常量

相对于变量,常量是恒定不变的值,多用于定义程序运行期间不会改变的那些值。 常量的声明和变量声明非常类似,只是把var换成了const,常量在定义的时候必须赋值。

const (
    n1 = 100
    n2
    n3
)

iota

iota是go语言的常量计数器,只能在常量的表达式中使用。

iota在const关键字出现时将被重置为0。const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。 使用iota能简化定义,在定义枚举时很有用。

例子:

const (
        n1 = iota //0
        n2        //1
        n3        //2
        n4        //3
    )
1. 使用 _ 跳过iota
 const (
     a = iota // 0
     _          
     c = iota // 2
     d           //3
 )

2.中间插队

const (
        n1 = iota //0
        n2 = 100  //100
        n3 = iota //2
        n4        //3
    )
    const n5 = iota //0

3.定义量级

const (
        _  = iota
        KB = 1 << (10 * iota)  //1024
        MB = 1 << (10 * iota)
        GB = 1 << (10 * iota)
        TB = 1 << (10 * iota)
        PB = 1 << (10 * iota)
    )

4.多个定义在一行

const (
        a, b = iota + 1, iota + 2 //1,2
        c, d                      //2,3
        e, f                      //3,4
    )
原文地址:https://www.cnblogs.com/tsboy/p/11110099.html