Go const

2021-04-17  本文已影响0人  JunChow520

常量

字面常量

const pi = 3.14159
const e = 2.7182

常量定义

const identifier [type] = value

类型推导

const (
    PI float64 = 3.1415926
    zero = 0.0
    size int64 = 1024
    eof = -1
)
const defaultMaxIdleConns = 2
const minReadBufferSize = 16
const maxConsecutiveEmptyReads = 100

常量赋值

常量是在编译时确定,因此不能使用变量为其赋值。可使用确定的字面量、字面量运算、内置函数运算、其他定义的常量,这些在编译时可以确定地内容为其赋值。

const (
    _  = iota
    KB = 1 << (10 * iota) //2^10
    MB = 1 << (10 * iota)//2^20
    GB = 1 << (10 * iota)//2^30
    TB = 1 << (10 * iota)//2^40
    PB = 1 << (10 * iota)//2^50
)
fmt.Println(KB, MB, GB, TB, PB) //1024 1048576 1073741824 1099511627776 1125899906842624
const mask = 1 << 3
fmt.Println(mask) //8
const (
    noDelay time.Duration = 0
    timeout               = time.Minute * 10
)

由于常量的运算是在编译期完成的,这样不仅可以减少运行时的工作,也方便其他代码的编译优化。当操作数是常量时,一些运行时的错误可以在编译时被发现,比如整数除零、字符串索引越界、任何导致无效浮点数的操作等。

批量定义

const (
    IPv4Len = 4
    IPv6Len = 6
)
const (
    statusOK = 200
    notFound = 404
)
const (
    ErrorCode = 0
    FailCode
)
log.Println(FailCode) //0

预定义常量

常量生成器

type Gender int
const (
    Secret Gender = iota
    Male
    Famale
)
log.Println(Famel) //2
const (
    c1 = iota
    c2 = 100
    c3 = iota
    c4
)
fmt.Println(c1, c2, c3, c4) //0 100 2 3
const (
    c1, c2 = iota + 1, iota + 2
    c3, c4 = iota + 3, iota + 4
)
fmt.Println(c1, c2, c3, c4) //1 2 4 5

枚举

type CompressionLevel int
const (
    DefaultCompression CompressionLevel = 0
    NotCompression CompressionLevel = -1
    BestSpeed CompressionLevel = -2
    BestCompression CompressionLevel = -3
)

作用域

type Weekday int
const (
    Sunday Weekday = iota
    Mondy
    Tuesday
    Thursday 
    Friday
    Saturday
    numbeOfWeekdays
)

无类型常量

Golang中常量有个不同寻常之处,虽然常量可以具有任意的基础类型,但许多常量并没有一个明确的基础类型。编译器为这些没有明确类型的数字常量提供了比基础类型更高精度的算术运算,至少有256bit的运算精度。

通过延迟明确常量的具体类型,不仅可以提供更高的运算精度,还可以直接用于更多的表达式而非显式的类型转换。

const (
    pi32  float32    = math.Pi
    pi64  float64    = math.Pi
    pi128 complex128 = math.Pi
)
上一篇下一篇

猜你喜欢

热点阅读