2018-10-09-go_const.md

常量

常量单个初始化

package main

import "fmt"

const p = "death & taxes"

func main() {

	const q = 42

	fmt.Println("p - ", p)
	fmt.Println("q - ", q)
}

常量的多个初始化

package main

import "fmt"

const (
	pi       = 3.14
	language = "Go"
)

func main() {
	fmt.Println(pi)
	fmt.Println(language)
}

iota

iota是golang语言的常量计数器,只能在常量的表达式中使用

  1. 常规用法
type Weekday int

const (
    Sunday Weekday = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
)
func main() {
	fmt.Println(Wednesday)
	fmt.Println(Thursday)
	fmt.Println(Friday)
}
  1. 跳过用法

使用下划线可以跳过枚举类型

type AudioOutput int
const (
    OutMute AudioOutput = iota // 0
    OutMono                       // 1
    OutStereo                     // 2
    _
    _
    OutSurround                // 5
)
func main() {
	fmt.Println(OutMute)
	fmt.Println(OutStereo)
	fmt.Println(OutSurround)
}
  1. 位掩码表达式

常用于处理状态切换

package main

import (
	"fmt"
)

type Flags uint

const (
	FlagUp           Flags = 1 << iota // is up
	FlagBroadcast                      // supports broadcast access capability
	FlagLoopback                       // is a loopback interface
	FlagPointToPoint                   // belongs to a point-to-point link
	FlagMulticast                      // supports multicast access capability
)

func IsUp(v Flags) bool     { return v&FlagUp == FlagUp }
func TurnDown(v *Flags)     { *v &^= FlagUp }
func SetBroadcast(v *Flags) { *v |= FlagBroadcast }
func IsCast(v Flags) bool   { return v&(FlagBroadcast|FlagMulticast) != 0 }

func main() {
	var v Flags = FlagMulticast | FlagUp
	fmt.Printf("%b %t\n", v, IsUp(v)) // "10001 true"
	TurnDown(&v)
	fmt.Printf("%b %t\n", v, IsUp(v)) // "10000 false"
	SetBroadcast(&v)
	fmt.Printf("%b %t\n", v, IsUp(v))   // "10010 false"
	fmt.Printf("%b %t\n", v, IsCast(v)) // "10010 true"
}
  1. 定义数量级
const (
    _ = 1 << (10 * iota)
    KiB // 1024
    MiB // 1048576
    GiB // 1073741824
    TiB // 1099511627776             (exceeds 1 << 32)
    PiB // 1125899906842624
    EiB // 1152921504606846976
    ZiB // 1180591620717411303424    (exceeds 1 << 64)
    YiB // 1208925819614629174706176
)
func main() {

	fmt.Println(KiB, TiB)
}

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦