Go语言中预定义常量iota的用法

Go语言中预定义了这些常量:true、false、iota.

iota可以被认为是一个可被编译器修改的常量,在每个const关键字出现时被重置为0,在下一个const出现之前,每出现一次iota,其所代表的数字会自增1.

示例:

package main
 
import "fmt"
 
const (
a = iota
b = iota
c = iota
d
e
)
 
const x = iota
const (
y = iota
z
)
 
func main() {
fmt.Println(a, b, c, d, e, x, y, z)
}

程序运行后会打印:

0 1 2 3 4 0 0 1

x,y值之所以为0,就是因为新出现了const关键字,iota被重置。

iota只能在常量的表达式中使用,不能当作变量使用。

a:= iota

会出现undefined: iota错误。

跳过部分值

我们可以使用某些方法跳过iota的某些值。

package main
 
import "fmt"
 
const x = iota
const (
y = iota
z
)
 
const (
_ = iota
a
b
_
_
c
)
 
func main() {
fmt.Println(a, b, c)
}

运行上面这段代码,输出为:1、2、5

常量表达式中的运用

const (
a = iota + 1 // 0+1
b            // 1+1
c            // 2+1
)

iota在同一行中的应用

iota值在同一行中的值不会发生改变:

package main
 
import "fmt"
 
const x = iota
const (
y = iota
z
)
 
const (
a, b = iota, iota
c, d
e, _
)
 
func main() {
fmt.Println(a, b, c, d, e)
}

运行上述代码,打印 0 0 1 1 2

const声明中,每行赋值都会使iota增1

const (
a = iota
b = 999
c = iota //这里需要使用iota
d
)

c值为2,d 为3。

原创内容,如需转载,请注明出处;

本文地址: https://www.perfcode.com/p/1469.html

分类: 计算机技术
推荐阅读:
Kali更新源的方法和优质国内源 所谓的Kali源,你可以将它理解为软件仓库,系统通过它安装和更新软件;源的服务器地址写在/etc/apt/sources.list文件中;当系统使用的当前源不可用或速度不理想时,就需要更换源;
PySide6改变界面主题风格 在本文中,您将学会如何使用QApplication的静态函数setStyle()更改PySide6的主题风格;
Python bool()函数详细教程 bool()函数用于对任何对象进行逻辑值的检测,返回True或False;
System has not been booted with systemd as init system (PID 1). Can't operate.解决方法 在WSL(Windows Subsystem for Linux,适用于Linux的Windows子系统)下通过systemctl命令启动某些服务将造成System has not been booted with systemd as init system (PID 1). Can't operate.这样的错误;
Golang安装gin库的详细教程及错误解决方法 Gin是用Go(Golang)编写的Web框架。 它具有类似于martini的API,其性能比httprouter快40倍。 如果您需要性能和良好的生产率,您会喜欢Gin
Rust中unwrap和expect的区别 在 Rust 中,unwrap() 和 expect() 是 Option 和 Result 类型(也可能是其他类型)提供的方法,用于从这些类型中获取包含的值。它们的区别在于如何处理潜在的错误。