Go语言学习笔记-04常量
定义
使用const
关键字定义常量,类型只能是布尔型,数字型,字符串型
只定义名称,缺省类型与赋值时,与同一个定义块的上一个常量保持一致
ch04/main.go
package main
import "fmt"
const a1 = 1
// 批量定义
const (
b1 = true
b2 = "a"
)
// 只定义名称,保持与上一个常量一致
const (
c1 = 1 //1
c2 //1
)
func main() {
fmt.Println("a1 =", a1)
fmt.Println("b1 =", b1)
fmt.Println("b2 =", b2)
fmt.Println("c1 =", c1)
fmt.Println("c2 =", c2)
}
上述代码输出
a1 = 1
b1 = true
b2 = a
c1 = 1
c2 = 1
常量的类型
没有显示指定类型时,使用常量的地方需要什么类型,则常量就是什么类型。(针对数字类型)
ch04/consttype/main.go
package main
import "fmt"
// 由使用的地方决定类型
const (
one = 1 // 1
two // 2
)
const (
Spring1 int64 = iota
// Summer1 保持与Spring1的定义一致
Summer1
)
const (
Spring2 int64 = iota
// Summer2 缺省类型,由使用的地方决定类型
Summer2 = iota
)
func main() {
var a1 = one
var a2 int32 = one
var a3 int32 = two
fmt.Printf("a1的类型为%T\n", a1)
fmt.Printf("a2的类型为%T\n", a2)
fmt.Printf("a3的类型为%T\n", a3)
fmt.Printf("Spring1的类型为%T\n", Spring1)
fmt.Printf("Summer1的类型为%T\n", Summer1)
fmt.Printf("Spring2的类型为%T\n", Spring2)
fmt.Printf("Summer2的类型为%T\n", Summer2)
}
上述代码输出
a1的类型为int
a2的类型为int32
a3的类型为int32
Spring1的类型为int64
Summer1的类型为int64
Spring2的类型为int64
Summer2的类型为int
iota
iota是go预定义关键字,可以方便地给常量赋值
每一个const
代码块内,iota的初始值为0,每增加一行,iota的值自增1,换言之,iota的值等于行号,行号从0开始计数
ch04/iota/main.go
package main
import "fmt"
// 每新增一行,iota自增1
const (
a1 = iota //0
a2 = iota //1
)
// 每一个const代码块,iota重置为0
const (
b1 = iota //0
)
const (
failed = iota //0
success //省略赋值,与上一个赋值一致,则为iota,同时新增了一行,则值为1
)
const (
zero = iota // 0
one // 1
five = 5 // 5
three = iota // 行号为3,则iota的值为3
)
func main() {
fmt.Println("a1 = ", a1)
fmt.Println("a2 = ", a2)
fmt.Println("b1 = ", b1)
fmt.Println("failed = ", failed)
fmt.Println("success = ", success)
fmt.Println("zero = ", zero)
fmt.Println("one = ", one)
fmt.Println("five = ", five)
fmt.Println("three = ", three)
}
上述代码输出
a1 = 0
a2 = 1
b1 = 0
failed = 0
success = 1
zero = 0
one = 1
five = 5
three = 3
笔记地址
github:https://github.com/xianyuyixi...
交流学习
微信号:xianyuyixia
微信公众号:闲渔一下