菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
0
0

go 中 iota 的使用

原创
05/13 14:22
阅读数 451

iota 的多种用法:

  1. iota 只能在常量的表达式中使用。例如:fmt.Println (iota) // 编译错误: undefined: iota

  2. 每次 const 出现时,都会让 iota 初始化为 0

        const a = iota // a=0 
        const ( 
              b = iota     //b=0 
              c            //c=1   相当于c=iota
        )
    
  3. 自定义类型,自增长常量经常包含一个自定义枚举类型,允许你依靠编译器完成自增设置

        type Stereotype int
        const ( 
            TypicalNoob Stereotype = iota // 0 
            TypicalHipster                // 1   TypicalHipster = iota
            TypicalUnixWizard             // 2  TypicalUnixWizard = iota
            TypicalStartupFounder         // 3  TypicalStartupFounder = iota
        )
    
    iota 在下一行增长,而不是立即取得它的引用。
    
        const (
            Apple, Banana = iota + 1, iota + 2    // Apple: 1  Banana: 2 
            Cherimoya, Durian   // = iota + 1, iota + 2   // Cherimoya: 2  Durian: 3 
            Elderberry, Fig     //= iota + 1, iota + 2    // Elderberry: 3    Fig: 4
        )
    
  4. 可跳过的值

        //如果两个const的赋值语句的表达式是一样的,那么可以省略后一个赋值表达式。
        type AudioOutput int
        const ( 
                OutMute AudioOutput = iota // 0 
                OutMono                    // 1 
                OutStereo                  // 2 
                _ 
                _ 
                OutSurround                // 5 
        )
    

    中间插队

        const ( 
            i = iota 
            j = 3.14 
            k = iota 
            l 
        )
        //那么打印出来的结果是 i=0,j=3.14,k=2,l=3
    
  5. 位掩码表达式

        type Allergen int
        const ( 
            IgEggs Allergen = 1 << iota         // 1 << 0 which is 00000001 
            IgChocolate                         // 1 << 1 which is 00000010 
            IgNuts                              // 1 << 2 which is 00000100 
            IgStrawberries                      // 1 << 3 which is 00001000 
            IgShellfish                         // 1 << 4 which is 00010000 
        )
    

发表评论

0/200
0 点赞
0 评论
收藏
为你推荐 换一批