29

GoLang 学习笔记 - 常量

 5 years ago
source link: https://www.tuicool.com/articles/VniqIzz
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

常量

  常量是在程序运行时不会被修改也不可修改的量。在GoLang 中,常量的数据类型只可以是布尔型、数值型(整数型、浮点型和复数)和字符串,通常用下划线分隔大写字母来命名常量。

  GoLang 中常量的定义格式:

const A string = "a"  // 显式类型定义
const B = "b"  // 隐式类型定义

  多个相同类型的声明可以简写为:

const NUM_1, NUM_2 = 3, 4

  常量还可以用作枚举(枚举篇会讲):

const (
    Unknown = 0
    Female = 1
    Male = 2
)

iota

  iota,特殊常量,可以认为是一个可以被编译器修改的常量,通常用作常量计数器。

  iota iota 每次出现都会初始化为 0,const 中每新增一行常量声明将使 iota 计数一次(iota 可理解为 const 语句块中的行索引)。

const a = iota  // a = 0 
const ( 
  b = iota  // b = 0 
  c  // c = 1   相当于 c = iota
)

  注意,iota 只能在常量表达式中使用

fmt.Println(iota)  // 编译错误: undefined: iota

    以上内容均源于网络,并加上自己的实践和理解,如有错误的地方,请在评论区指正。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK