常量
常量和变量不同,变量是可以赋值进行修改的,而常量是不能修改的。在使用中有一些值是我们不希望更改的,就可以声明成常量。通常,我们习惯与将常量写为大写。
定义一个常量
常量可以定义在函数体内和函数体外
| const name string = "mark" |
| fmt.Println(name) |
运行
| [root@LinuxEA /opt/Golang] |
| mark |
如果进行赋值修改就会报错
| |
| ./04.go:6:7: cannot assign to name |
省略类型
| const PP = 32132.21 |
| fmt.Println(PP) |
运行
| [root@LinuxEA /opt/Golang] |
| 32132.21 |
定义多个类型相同的常量
| const P1,P2 int = 3,4 |
| fmt.Println(P1,P2) |
运行
| [root@LinuxEA /opt/Golang] |
| 3 4 |
定义多个类型不相同的常量
| const ( |
| P1 string = "mark" |
| P2 int = 4 |
| ) |
| fmt.Println(P1,P2) |
运行
| [root@LinuxEA /opt/Golang] |
| mark 4 |
定义多个常量省略类型
| const ( |
| P1 = "mark" |
| P2 = 4 |
| P3 = 32.1 |
| ) |
| fmt.Println(P1,P2,P3) |
运行
| [root@LinuxEA /opt/Golang] |
| mark 4 32.1 |
赋值省略
在go中,如果产量的第一个值和最后一个值都是一样的,就可以省略掉。如下:
| const ( |
| P1 = 1 |
| P2 |
| P3 |
| ) |
| fmt.Println(P1,P2,P3) |
运行
| [root@LinuxEA /opt/Golang] |
| 1 1 1 |
还可以像这样
| const ( |
| P1 = "mark" |
| P2 |
| P3 |
| P100 = 3.5 |
| P101 |
| C11 = 123 |
| C12 |
| ) |
| fmt.Println(P1,P2,P3,P100,P101,C11,C12) |
运行
| [root@LinuxEA /opt/Golang]# go run 04.go |
| mark mark mark 3.5 3.5 123 123 |
枚举
这种方式可以应用在枚举上,const+iota
枚举是以const()括号内部开始和结束的。不影响到括号外的操作。
| const ( |
| B1 int = iota |
| B2 |
| B3 |
| B4 |
| ) |
| fmt.Println(B1,B2,B3,B4) |
运行
| [root@LinuxEA /opt/Golang] |
| 0 1 2 3 |