Go变量类型与 const, iota
变量
变量类型
- string
- int
- float
- bool ( int 不能转换为 bool )
- nil
变量声明
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70package main
/*
四种变量的声明方式
*/
import (
"fmt"
)
//声明全局变量 方法一、方法二、方法三是可以的
var gA int = 100
var gB = 200
//用方法四来声明全局变量
// := 只能够用在 函数体内来声明
//gC := 200
func main() {
//方法一:声明一个变量 默认的值是0
var a int
fmt.Println("a = ", a)
fmt.Printf("type of a = %T\n", a)
//方法二:声明一个变量,初始化一个值
var b int = 100
fmt.Println("b = ", b)
fmt.Printf("type of b = %T\n", b)
var bb string = "abcd"
fmt.Printf("bb = %s, type of bb = %T\n", bb, bb)
//方法三:在初始化的时候,可以省去数据类型,通过值自动匹配当前的变量的数据类型
var c = 100
fmt.Println("c = ", c)
fmt.Printf("type of c = %T\n", c)
var cc = "abcd"
fmt.Printf("cc = %s, type of cc = %T\n", cc, cc)
//方法四:(常用的方法) 省去var关键字,直接自动匹配
e := 100
fmt.Println("e = ", e)
fmt.Printf("type of e = %T\n", e)
f := "abcd"
fmt.Println("f = ", f)
fmt.Printf("type of f = %T\n", f)
g := 3.14
fmt.Println("g = ", g)
fmt.Printf("type of g = %T\n", g)
// =====
fmt.Println("gA = ", gA, ", gB = ", gB)
//fmt.Println("gC = ", gC)
// 声明多个变量
var xx, yy int = 100, 200
fmt.Println("xx = ", xx, ", yy = ", yy)
var kk, ll = 100, "Aceld"
fmt.Println("kk = ", kk, ", ll = ", ll)
//多行的多变量声明
var (
vv int = 100
jj bool = true
)
fmt.Println("vv = ", vv, ", jj = ", jj)
}
输出
fmt.Printf()
等
%d
,%f
,%s
%x
输出地址%T
输出类型%v
输出数组,map,结构体等const 与 iota
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44package main
import "fmt"
//const 来定义枚举类型
const (
//可以在const() 添加一个关键字 iota, 每行的iota都会累加1, 第一行的iota的默认值是0
BEIJING = 10*iota //iota = 0
SHANGHAI //iota = 1
SHENZHEN //iota = 2
)
const (
a, b = iota+1, iota+2 // iota = 0, a = iota + 1, b = iota + 2, a = 1, b = 2
c, d // iota = 1, c = iota + 1, d = iota + 2, c = 2, d = 3
e, f // iota = 2, e = iota + 1, f = iota + 2, e = 3, f = 4
g, h = iota * 2, iota *3 // iota = 3, g = iota * 2, h = iota * 3, g = 6, h = 9
i, k // iota = 4, i = iota * 2, k = iota * 3 , i = 8, k = 12
)
func main() {
//常量(只读属性)
const length int = 10
fmt.Println("length = ", length)
//length = 100 //常量是不允许修改的。
fmt.Println("BEIJIGN = ", BEIJING)
fmt.Println("SHANGHAI = ", SHANGHAI)
fmt.Println("SHENZHEN = ", SHENZHEN)
fmt.Println("a = ", a, "b = ", b)
fmt.Println("c = ", c, "d = ", d)
fmt.Println("e = ", e, "f = ", f)
fmt.Println("g = ", g, "h = ", h)
fmt.Println("i = ", i, "k = ", k)
// iota 只能够配合const() 一起使用, iota只有在const进行累加效果。
//var a int = iota
}