常量和变量
文件名&关键字&标识符
- 所有go源码以.go结尾
- 标识符以字母或下划线开头,大小写敏感,比如:
a. boy √
b. Boy √
c. a+b x
d. Oboy √
e. _boy √
f. =_boy x
g. _ √ //特殊的标识符,a,_,b,意思是不取值
- _是特殊标识符,用来忽略结果
- 保留关键字
break | default | func | interface | select(用在chann管道里面) |
---|---|---|---|---|
case | defer | go | map | struct |
chan | else | goto | package | switch |
const(声明一个常量) | fallthough | if | range | type |
continue | for | import | return | var |
- 37和保留字
Constants: true false iota nil
Types: int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
float32 float64 complex128 complex64
bool byte rune string error
Functions: make len cap new append copy close delete
complex real imag
panic recover
常量
1.常量使用const修饰,代表永远是只读的,不能修改
2.const只能修饰boolean,number(int类型,浮点类型,complex)和string
3.语法: const identifier [type] = value,其中type可以省略
//举例:
const b string = "hello world"
const b = "hello world"
const Pi = 3.1415926
const a = 9/3
const c = getValue() //这是错误的,不能是一个函数
4.比较优雅的写法:
const(
a=0
b=1
c=2
)
5.更专业的写法:
const(
a=iota
b //1
c //2
)
iota的使用
iota
是go语言的常量计数器,只能在常量的表达式中使用。
iota
在const关键字中出现时将被重置为行索引值。const中每新增一行常量声明将使iota
计数一次(iota可理解为const语句块中的行索引)。 使用iota能简化定义,在定义枚举时很有用。
const (
a = 3.2323232
c = iota //1
d //2
e = iota //3
f //4
)
// 多个常量声明在一行
const (
d1, d2 = iota + 1, iota + 2 // d1:1 d2:2
d3, d4 = iota + 1, iota + 2 // d3:2 d4:3
)
const (
a, b = iota, iota //0 0
d = iota // 1
)
iota的数量级使用
const (
_ = iota // 0
KB = 1 << (10 * iota) // 1向左边移动10位,变成1000000000,2的10次方,也就是1024
MB = 1 << (10 * iota) // 1向左边移动20位
GB = 1 << (10 * iota)
TB = 1 << (10 * iota)
PB = 1 << (10 * iota)
)
变量
var (
a int //默认是0
b string //默认是""
c bool //默认是false
d int = 8
e string="hello world"
)
var (
a int //默认是0
b string //默认是""
c bool //默认是false
d = 8 //可以不加类型,go会自动推导出值的类型
e ="hello world"
)