清水泥沙

golang基础(6.常量和枚举)

常量指的是在编译期间已知的且不可改变的数据类型,常量可以是数值类型、浮点型、复合类型、布尔类型、字符串类型,在go中任何编译器后试图改变常量的操作都会导致编译报错。

定义常量

在go中我们可以使用const来定义常量,以下是常见的击中定义方式

package _const

const Pi float64 = 3.14159265358979323846
const zero = 0.0 // 无类型浮点常量
const (          // 通过一个 const 关键字定义多个常量,和 var 类似
	size int64 = 1024
	eof = -1  // 无类型整型常量
)
const u, v float32 = 0, 3  // u = 0.0, v = 3.0,常量的多重赋值
const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", 无类型整型和字符串常量

预定义常量

go中预定义的常量有 true,false,iotaiota比较特殊,它是一个可以被编译器修改的常量。在编译期间每次const关键字出现时iota都会被重置为0,直到下一个const出现前,每出现一次iota都会递增。

package main

import "fmt"

const (
	a1 = iota
	a2 = iota
	a3 = iota
)

const (
	b1 = iota * 2
	b2 = iota * 2
	b3 = iota * 2
)

const (
	c1 = iota * 3
	c2
	c3
)

func main() {
	fmt.Printf("a1 is %d 
", a1)
	fmt.Printf("a2 is %d 
", a2)
	fmt.Printf("a3 is %d 
", a3)
	fmt.Printf("b1 is %d 
", b1)
	fmt.Printf("b2 is %d 
", b2)
	fmt.Printf("b3 is %d 
", b3)
	fmt.Printf("c1 is %d 
", c1)
	fmt.Printf("c2 is %d 
", c2)
	fmt.Printf("c2 is %d 
", c3)
}

枚举

go中并没有其他语言类似的enum 关键字,而是通过,const后跟一对圆括号定义一组常量的方式来实现枚举。

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

常量作用域

跟变量一致,以大写开头的常量是可以在当前包和外部包进行访问的(public),以小写开头的常量只能在当前包中进行访问。