目录
三、常量
3.1、字面常量
即程序中硬编码的常量,如:
-12 //整形常量
3.1415926 //浮点型常量
3.2+12i //复数型常量
true //布尔型常量
"foo" //字符串常量
//注:
//在其它语言中,常量通常有特定的类型,比如 -12 在 c 语言中会认为是一个 int 型常量。
//如果要指定一个值为 -12 的 long 类型常量,需要写成 -12l,这有点儿违背人们的直观感觉。
//go语言中的字面常量更接近我们自然语言中的常量概念,它是无类型的,只要这个常量在相应
//类型的值域范围内,就可以作为该类型的常量。比如上面的常量 -12,它可以赋值给 int,
//int32, int64, float32, float64, complex32, complex64, complex128 等类型的常量。
3.2、常量定义
package main
import (
"fmt"
)
const Pi float64 = 3.14159265358979323846 //float64的浮点型常量
const zero = 0.0 //无类型浮点常量
const (
size int64 = 1024 //int64的整型常量
eof = -1 //无类型整形常量
)
//常量的多重复值
const v, u float32 = 0, 3 //v=0.0, u=3.0
//无类型整形和字符串常量
const a, b, c = 3, 4, "foo" //a=3, b=4, c="foo"
func main() {
//zero=0 and it's type is float64
fmt.Printf("zero=%v and it's type is %T\n", zero, zero)
//v=0 and it's type is float32
fmt.Printf("v=%v and it's type is %T\n", v, v)
//u=3 and it's type is float32
fmt.Printf("u=%v and it's type is %T\n", u, u)
//a=3 and it's type is int
fmt.Printf("a=%v and it's type is %T\n", a, a)
//b=4 and it's type is int
fmt.Printf("b=%v and it's type is %T\n", b, b)
//c=foo and it's type is string
fmt.Printf("c=%v and it's type is %T\n", c, c)
}
3.3、预定义常量
Go语言预定义了这些常量:
true, false 和 iota
iota比较特殊,可以被认为是一个可被编译器修改的常量,在每一个 const 关键字出现时被重置为0,
然后在下一个 const 出现之前,每出现一次 iota,其所代表的数字会自增 1 。
示例用法:
const ( //const每次出现,iota被重置为0
c0 = iota //c0==0
c1 = iota //c1==1
c2 = iota //c2==2
)
const ( //const每次出现,iota被重置为0
a = 1 << iota //iota左移一位,变成1
b = 1 << iota //iota在左移一位,变成2
c = 1 << iota //iota在左移一位,变成4
)
//如果两个 const 的赋值语句表达式是一样的,那么可以省略后一个赋值表达式,因此上面两个 const 语句可简写为:
const (
c0 = iota //c0==0
c1 //c1==1
c2 //c2==2
)
const (
a = 1 << iota //a==1
b //b==2
c //c==4
)
3.4、枚举
枚举指一系列相关的常量
可以用在const后跟一对圆括号的方式定义一组常量,这种定义法也可以用来定义一组枚举值
go语言不支持enum关键字
比如下面关于一个星期中每天的定义
const (
Sunday = iota //以大写字母开头的常量在包外可见
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
numberOfDays //这个常量是以小写字母开头,为包内私有
)
注:这篇博文是我学习《go语言编程》一书后,边学习边实际尝试后所写,如有转载请注明出处:https://blog.csdn.net/DaiChuanrong/article/details/115107326
上一篇:go变量
下一篇:Go运算符