constants

constants

  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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main

import "fmt"

// 无类型常量
const B10 = false
const I10 = 1
const F10 = 1.2

// 有类型常量
const B20 bool = true
const I20 int8 = 1
const F20 float32 = 1.2

// 使用iota
const (
	AI = iota + 1
	BI
	CI
	_
	DI
)

func main() {
	fmt.Printf("%v,%T\n", B10, B10)
	fmt.Printf("%v,%T\n", I10, I10)
	fmt.Printf("%v,%T\n", I10, I10)

	fmt.Printf("%v,%T\n", B20, B20)
	fmt.Printf("%v,%T\n", I20, I20)
	fmt.Printf("%v,%T\n", F20, F20)

	fmt.Printf("%v,%T\n", AI, AI)
	fmt.Printf("%v,%T\n", BI, BI)
	fmt.Printf("%v,%T\n", CI, CI)
	fmt.Printf("%v,%T\n", DI, DI)

	// 无类型常量
	const b10 = false
	const i10 = 1
	const f10 = 1.2

	// 有类型常量
	const b20 bool = true
	const i20 int8 = 1
	const f20 float32 = 1.2

	// (1)使用iota
	const (
		ai = iota + 1
		bi
		ci
		_
		di
	)

	// (2)使用iota
	const (
		t1 = iota
		t2
		t3
		_
		t4 = "abcde"
		t5
		t6 = iota
		t7
	)

	fmt.Printf("%v,%T\n", b10, b10)
	fmt.Printf("%v,%T\n", i10, i10)
	fmt.Printf("%v,%T\n", f10, f10)

	fmt.Printf("%v,%T\n", b20, b20)
	fmt.Printf("%v,%T\n", i20, i20)
	fmt.Printf("%v,%T\n", f20, f20)

	fmt.Printf("%v,%T\n", ai, ai)
	fmt.Printf("%v,%T\n", bi, bi)
	fmt.Printf("%v,%T\n", ci, ci)
	fmt.Printf("%v,%T\n", di, di)

	fmt.Printf("%v,%T\n", t1, t1)
	fmt.Printf("%v,%T\n", t2, t2)
	fmt.Printf("%v,%T\n", t3, t3)
	fmt.Printf("%v,%T\n", t4, t4)
	fmt.Printf("%v,%T\n", t5, t5)
	fmt.Printf("%v,%T\n", t6, t6)
	fmt.Printf("%v,%T\n", t7, t7)
}

// Output:
//false,bool
//1,int
//1,int
//true,bool
//1,int8
//1.2,float32
//1,int
//2,int
//3,int
//5,int
//false,bool
//1,int
//1.2,float64
//true,bool
//1,int8
//1.2,float32
//1,int
//2,int
//3,int
//5,int
//0,int
//1,int
//2,int
//abcde,string
//abcde,string
//6,int
//7,int
最后修改 July 13, 2024: 更新 (5485dd5)