【Golang】golang的一些知识要点

特殊常量iota:

  1.iota的值在遇到const关键字时将被重置为0

  2.const中每新增一行常量声明将使iota计数一次,也就是自动加一。

  3.iota只能在常量定义中使用。

iota常见使用方法:

   1.跳值使用法;

   2.插队使用法;

   3.表达式隐式使用法;

   4.单行使用法;

package main
import (
    "fmt"
)
const a = iota
const b = iota
func main() {
    fmt.Println("a的常量值为",a)     //值为0
    fmt.Println("b的常量值为",b)     //值为0
}
package main

import (
    "fmt"
)

const a = iota
const (
   b = iota
   c = iota
)
func main() {
    fmt.Println("a的常量值为",a)   //值为0
    fmt.Println("b的常量值为",b)   //值为0
    fmt.Println("c的常量值为",c)   //值为1
}

 所以每新增一行常量声明,这里iota自增一

跳值使用法

以上代码省略....

const (
   a = iota
   b = iota
   _
   c = iota
)
func main() {
    fmt.Println("a的常量值为",a)  //值为0
    fmt.Println("b的常量值为",b)  //值为1
    fmt.Println("c的常量值为",c)  //值为3
}

插队使用法

const (
   a = iota
   b = 3
   c = iota
)
func main() {
    fmt.Println("a的常量值为",a)   //值为0
    fmt.Println("b的常量值为",b)   //值为3
    fmt.Println("c的常量值为",c)   //值为2
}

 表达式隐式使用法

const (
   a = iota * 2
   b = iota
   c = iota
)
func main() {
    fmt.Println("a的常量值为",a)   //值为0
    fmt.Println("b的常量值为",b)   //值为1
    fmt.Println("c的常量值为",c)   //值为2
}
const (
   a = iota * 2
   b             // 1*2   自动隐士的继承上面非空表达式
   c             // 2*2
)
func main() {
    fmt.Println("a的常量值为",a)  //值为0
    fmt.Println("b的常量值为",b)  //值为2
    fmt.Println("c的常量值为",c)  //值为4 
}
const (
   a = iota * 2
   b = iota * 3
   c 
)
func main() {
    fmt.Println("a的常量值为",a)   //值为0
    fmt.Println("b的常量值为",b)   //值为3
    fmt.Println("c的常量值为",c)   //值为6
}

单行使用法

const (
   a,b = iota,iota * 2  //同一行iota的值是不加的
   c,d                  //c引用的是a,而不是后面的b iota * 2 
   e = iota             //这行e只有单独一个 因为格式和上面不一样,编辑器会报错,所以要赋值iota 
)
func main() {
    fmt.Println("a的常量值为",a)    //值为0
    fmt.Println("b的常量值为",b)    //值为0
    fmt.Println("c的常量值为",c)    //值为1
    fmt.Println("d的常量值为",d)    //值为2
    fmt.Println("e的常量值为",e)    //值为2
}
原文地址:https://www.cnblogs.com/songgj/p/10657221.html