您的位置 首页 golang

Golang基础之常量

常量-该内存块中数据不可改变,多用于定义程序运行期间不会改变的那些值。

1、常量的定义,使用关键字const

const age int = 18 //显式类型定义

const Pi = 3.141 // 隐式类型定义

const (

size int64 = 1024

accessKeyID = “abc”

)

2、iota

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

每一个iota出现时,常量都会被重置为0

如:源码log/log.go中

const (

Ldate = 1 << iota // the date in the local time zone: 2009/01/23

Ltime // the time in the local time zone: 01:23:23

Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.

Llongfile // full file name and line number: /a/b/c/d.go:23

Lshortfile // final file name element and line number: d.go:23. overrides Llongfile

LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone

LstdFlags = Ldate | Ltime // initial values for the standard logger

)

用于定义log级别

type Level int8

const (

LevelDebug Level = iota

LevelInfo

LevelWarn

LevelError

LevelFatal

LevelPanic

)

3、注意

由于常量不可变性,所以常量值在编译过程中就得确定,如果常量是一个赋值表达式,表达式结果也必须在编译期获取到结果。

const peroid = 3600/10 // 通过

const home = os.GetEnv(“HOME”) // 不通过

文章来源:智云一二三科技

文章标题:Golang基础之常量

文章地址:https://www.zhihuclub.com/100132.shtml

关于作者: 智云科技

热门文章

网站地图