11

Go-004 常量

 4 years ago
source link: https://studygolang.com/articles/26726
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.

1 概述

一旦定义,其值不可更改的量,称之为常量。也是常量标识符和常量值。

常量用于存储简单数据类型:数值,字符串。

2 定义

语法:const c1 string = “GoLang”

语法上,支持批量定义,支持类型推导:

const (
    c1 int = 42
    c2 = 42
    c3 = "golang"
)
fmt.Println(c1,c2,c3)

注意: 批量定义,若 后边的只写常量名,则代表和上一个一致

const (
    c1  = 42
    c2
    c3
)
fmt.Println(c1,c2,c3)  // 42 42 42

3 使用常量的意义

  • 防止被无意的修改。
  • 将特定的数据语义化。

例如错误处理,使用不同的数值,表示不同的错误级别,如下所示:

// 1023 表示全部的错误级别
// 4 表示提示级别。
const (
    errorAll = 1023 
    errorNotice = 4
)
// 设置错误级别 
setErrorLevel(1023)
setErrorLevel(errorAll)

4.iota 常量

4.1 概述

用于定义批量常量时,iota 表示基于行的从 0 开始逐一递增的序列数, 即 行索引

演示:

const (
    c1  = iota
    c2 = iota
    c3 = iota
)
fmt.Println(c1,c2,c3) // 0, 1, 2

注意: 一定基于行的,即使我们没全部使用 iota 进行定义,iota 还是代表行索引。

const (
    c1  = 42
    c2 = 1024
    c3 = iota
)
fmt.Println(c1,c2,c3) // 42, 1024, 2

4.2 一个典型的应用

结合位运算的错误配置,后续讲解位运算时进行更详细的讲解

const (
    errorNotice  = 1 << iota
    errorWarning 
    errorFatal
)
fmt.Println(errorNotice, errorWarning, errorFatal) //

以上定义使用了如下的技巧:

  • 常量的批量定义
  • 利用了iota行索引值
  • 批量定义中,常量延续前面的常量定义
  • << 位运算符。

对应的展开语法为:

const (
    errorNotice  = 1 << 0  // 001  1
    errorWarning  = 1 << 1  // 010  2
    errorFatal = 1 << 2 // 100 4
)
fmt.Println(errorNotice, errorWarning, errorFatal) //

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK