关于golang:Go-语言学习之常量

35次阅读

共计 1676 个字符,预计需要花费 5 分钟才能阅读完成。

01 概念

常量是一种表达式,常量的计算能够在编译时实现,如果有谬误,在编译时就会报错,常量的值不能够批改。

02 申明常量

常量申明能够同时指定类型和值,如果没有显示指定类型,则类型依据左边的表达式推断。须要特地留神的是,申明常量不同于申明变量能够不赋值,申明常量必须赋值。

const name string = "golang"
const PI = 3.14

func main() {fmt.Printf("name = %s type:%T\n", name, name)
  fmt.Printf("PI = %g type:%T\n", PI, PI)
}

申明一组常量,每个常量类型能够不同。

const (
  x = 1
  y = "hello"
  z = true
)

func main() {fmt.Printf("x = %d type:%T\n", x, x)
  fmt.Printf("y = %s type:%T\n", y, y)
  fmt.Printf("z = %t type:%T\n", z, z)
}

申明一组常量,除了第一个常量之外,其余常量都能够省略表达式,其余常量会复用其后面一个常量的类型和表达式。

const (
  a = 1
  b
  c = 2
  d
)

func main() {fmt.Printf("a = %d type:%T\n", a, a)
  fmt.Printf("b = %d type:%T\n", b, b)
  fmt.Printf("c = %d type:%T\n", c, c)
  fmt.Printf("d = %d type:%T\n", d, d)
}

03 常量生成器 iota

申明一组常量,能够应用常量生成器 iota,它能够不必一一常量显示指定类型和赋值表达式,常量申明中,iota 从 0 开始取值,后续常量如果没有显示指定类型和赋值表达式,其值是其后面一个常量的值加 1。直到遇到赋值常量进行加 1,后续如果再遇到赋值 iota 的常量,则持续一一加 1。

const (
  Sunday int = iota
  Monday
  Tuesday
  Wednesday
  Thursday
  Friday
  Saturday
)

const (
  aa int = iota
  bb
  cc
  dd = 10
  ee
  ff = iota
  gg
  hh
)

func main() {fmt.Printf("Sunday = %d type:%T\n", Sunday, Sunday)
  fmt.Printf("Monday = %d type:%T\n", Monday, Monday)
  fmt.Printf("Tuesday = %d type:%T\n", Tuesday, Tuesday)
  fmt.Printf("Wednesday = %d type:%T\n", Wednesday, Wednesday)
  fmt.Printf("Thursday = %d type:%T\n", Thursday, Tuesday)
  fmt.Printf("Friday = %d type:%T\n", Friday, Friday)
  fmt.Printf("Saturday = %d type:%T\n", Saturday, Saturday)
  fmt.Printf("aa = %d type:%T\n", aa, aa)
  fmt.Printf("bb = %d type:%T\n", bb, bb)
  fmt.Printf("cc = %d type:%T\n", cc, cc)
  fmt.Printf("dd = %d type:%T\n", dd, dd)
  fmt.Printf("ee = %d type:%T\n", ee, ee)
  fmt.Printf("ff= %d type:%T\n", ff, ff)
  fmt.Printf("gg = %d type:%T\n", gg, gg)
  fmt.Printf("hh = %d type:%T\n", hh, hh)
}

04 无类型常量

无类型常量,能够间接赋值给其余常量,显示指定类型的常量,赋值给其余常量时,会做强类型查看。

const username, age = "lucy", 17
const user = username

func main() {fmt.Printf("username = %s, age = %d\n", username, age)
  fmt.Printf("user = %s\n", user)
}

Go 语言基础知识

正文完
 0