Golang基础随笔(1)

35 阅读1分钟

1. 常量

定义格式为:

const identifier [type] = value

举例比如:

const username string = "cscs"

也可写为:

const username = "cscs"

同时,常量可作为枚举使用:

const (
    Unknown = 0
    Female = 1
    Male = 2
)

常量可通过len(),unsafe.sizeof()进行取值:

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    const username = "cscs"
    fmt.Println(len(username))           // 字符串长度 4
    fmt.Println(unsafe.Sizeof(username)) // 在内存中占的字节数(字符串在go中为结构体) 16
}

2.iota(特殊常量)

iota 在 const关键字出现时将被重置为 0(const 内部的第一行之前),const 中每新增一行常量声明将使 iota 计数一次 (iota 可理解为 const 语句块中的行索引)。 iota通常作为枚举使用:

package main

import "fmt"

const (
    a = iota
    b = iota
    c = iota
)

func main() {
    fmt.Println(a, b, c) // 0 1 2
}

可简写为以下形式:

const (
    a = iota
    b = 
    c = 
)
package main

import  "fmt"

func main() {
  const (
      a = iota  //0
      b         //1
      c         //2
      d = "ha"  //独立值,iota += 1
      e         //"ha"  iota += 1
      f = 100   //iota +=1
      g         //100  iota +=1
      h = iota  //7,恢复计数
      i         //8
  )
  fmt.Println(a,b,c,d,e,f,g,h,i)
}