要点
- 用const定义常量
- iota 表示取值为0(const关键字)所在行,后续常量依次加1
- iota 用来表示递增的数列,用法较多,参考下面的示例代码。
示例代码
package main
import (
"fmt"
)
/*
The Go Programming Language. 3.6 Constants
When a sequence of constants is declared as a group, the right-hand
side expression may be omitted for all but the first of the group,
implying that the previous expression and its type should be used
again. For example:
*/
func foo() {
const (
a = 1
b
c = 2
d
)
fmt.Println(a, b, c, d) // "1 1 2 2"
}
/*
3.6.1. The Constant Generator iota
A const declaration may use the constant generator iota, which is used
to create a sequence of related values without spelling out each one
explicitly. In a const declaration, the value of iota begins at zero
and increments by one for each item in the sequence.
*/
func bar() {
type ErrorCode int
const (
ERROR_SUCCESS ErrorCode = iota
ERROR_FIRST
ERROR_SECOND
ERROR_THIRD
)
error_code := ERROR_SUCCESS
fmt.Println("default: ", error_code) // default: 0
error_code = ERROR_SECOND
fmt.Println("Second: ", error_code) // Second: 2
}
/*
As iota increments, each constant is assigned the value of 1 << iota,
which evaluates to suc- cessive powers of two, each corresponding to a single bit.
FlagBroadcast: 2
FlagLoopback: 4
FlagPointToPoint: 8
FlagMulticast: 16
*/
func baz() {
type Flags uint
const (
FlagUp Flags = 1 << iota // is up
FlagBroadcast // 1 << 1 = 2^1 = 2, supports broadcast access capability
FlagLoopback // 1 << 2 = 2 ^ 2 = 4, is a loopback interface
FlagPointToPoint // 1 << 3 = 2 ^ 3 = 8, belongs to a point-to-point link
FlagMulticast // 1 << 4 = 2 ^ 4 = 16, supports multicast access capability
)
fmt.Println("FlagUp: ", FlagUp)
fmt.Println("FlagBroadcast: ", FlagBroadcast)
fmt.Println("FlagLoopback: ", FlagLoopback)
fmt.Println("FlagPointToPoint: ", FlagPointToPoint)
fmt.Println("FlagMulticast: ", FlagMulticast)
}
/*
As a more complex example of iota, this declaration names the powers of 1024.
KiB: 1024
MiB: 1048576
GiB: 1073741824
TiB: 1099511627776
PiB: 1125899906842624
EiB: 1152921504606846976
*/
func qux() {
const (
_ = 1 << (10 * iota)
KiB // 1 << (10 * 1) = 1 << 10 = 2^10 = 1024
MiB // 1 << (10 * 2) = 1 << 20 = 2^20 = 1024 * 1024 = 1048576
GiB // 1 << (10 * 3) = 1 << 30 = 2^30 = 1024^3 = 1073741824
TiB // 1099511627776
PiB // 1125899906842624
EiB // 1152921504606846976
//ZiB // 1180591620717411303424 //constant 1180591620717411303424 overflows int
//YiB // 1208925819614629174706176 //constant 1208925819614629174706176 overflows int
)
fmt.Println("KiB: ", KiB)
fmt.Println("MiB: ", MiB)
fmt.Println("GiB: ", GiB)
fmt.Println("TiB: ", TiB)
fmt.Println("PiB: ", PiB)
fmt.Println("EiB: ", EiB)
//fmt.Println("ZiB: ", ZiB)
//fmt.Println("YiB: ", YiB)
}
func main() {
foo()
bar()
baz()
qux()
}
有疑问加站长微信联系(非本文作者)