【Golang 基础系列九】Go 语言的枚举 - Go语言中文社区

【Golang 基础系列九】Go 语言的枚举


在这里插入图片描述

概述

将变量的值一一列举出来,变量只限于列举出来的值的范围内取值

Go语言中没有枚举这种数据类型的,但是可以使用const配合iota模式来实现

一、普通枚举

const (
	 cpp = 0
	 java = 1
	 python = 2
	 golang = 3
)

二、自增枚举

  1. iota只能在常量的表达式中使用

    fmt.Println(iota)  //undefined: iota
    
  2. 它默认开始值是0,const中每增加一行加1

    const (
            a = iota  //0
            c         //1
            d         //2
        )
    
  3. 每次 const 出现时,都会让 iota 初始化为0

    const d = iota    // a=0
    const (
    	  e = iota     //b=0
    	  f            //c=1
    )
    
  4. 如果中断iota,必须显式恢复!!!

    const ( 
    
        Low = iota    //0
    
        Medium        //1
    
        High = 100   //100
    
        Super        //100
    
        Band = iota  //4
    
    )
    
  5. 如果是同一行,值都一样

    const (
    i          = iota
    j1, j2, j3 = iota, iota, iota
    k          = iota
    )
    
  6. 可跳过的值

    const (
    		k1 = iota // 0
    		k2        // 1
    		_         //2
    		_         //3
    		k3       // 4
    	)
    
  7. 中间插入一个值

    const (
    	Sun = iota //Sun = 0
    	Mon        // Mon = 1
    	Tue = 7    //7
    	Thu = iota // 3
    	Fri        //4
    )
    

三、注意:

  1. iota 必须配合const 使用,否则undefined: iota
  2. 每次 const 出现时,都会让 iota 初始化为0
  3. 如果是同一行,值都一样

四、代码

package main

import "fmt"

func main() {

	//普通枚举
	const (
		cpp    = 0
		java   = 1
		python = 2
	)
	fmt.Printf("cpp=%d  java=%d  python=%dn", cpp, java, python) //a=0  b=1  c=2


	//1.iota只能在常量的表达式中使用
	//fmt.Println(iota)  //undefined: iota


	//2.它默认开始值是0,const中每增加一行加1
	const (
		a = iota //0
		b        //1
		c        //2
	)

	fmt.Printf("a=%d  b=%d  c=%dn", a, b, c) //a=0  b=1  c=2



	//3.每次 const 出现时,都会让 iota 初始化为0
	const d = iota // a=0
	const (
		e = iota //b=0
		f        //c=1
	)
	fmt.Printf("d=%d  e=%d  f=%dn", d, e, f) //d=0  e=0  f=1


	//4.如果中断iota,必须显式恢复!!!
	const (
		Low = iota //0

		Medium //1

		High = 100 //100

		Super //100

		Band = iota //4

	)
	//Low=0  Medium=1  High=100  Super=100  Band=4
	fmt.Printf("Low=%d  Medium=%d  High=%d  Super=%d  Band=%dn", Low, Medium, High, Super, Band)


	//5.如果是同一行,值都一样
	const (
		i          = iota
		j1, j2, j3 = iota, iota, iota
		k          = iota
	)
	//i=0  j1=1  j2=1  j3=1  k=2
	fmt.Printf("i=%d  j1=%d  j2=%d  j3=%d  k=%dn", i, j1, j2, j3, k)


	//6.可跳过的值
	const (
		k1 = iota // 0
		k2        // 1
		_         //2
		_         //3
		k3        // 4
	)
	//	k1=0  k2=1  k3=4
	fmt.Printf("k1=%d  k2=%d  k3=%d n", k1, k2, k3)


	//7.中间插入一个值
	const (
		Sun = iota //Sun = 0
		Mon        // Mon = 1
		Tue = 7    //7
		Thu = iota // 3
		Fri        //4
	)
	//Sun=0  Mon=1  Tue=7  Thu=3  Fri=4
	fmt.Printf("Sun=%d  Mon=%d  Tue=%d  Thu=%d  Fri=%dn", Sun, Mon, Tue, Thu, Fri)

}
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/guofeng93/article/details/90766400
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢