Use of Golang—iota
1. Basic concepts
iota is a special variable in golang
It can only be used when the constant is defined, and an error will be reported when used in other places
1. Iota const
will be reset to 0 whenever encountered
as follows:
package main
import "fmt"
const a = iota
const b = iota
func main(){
fmt.Print("a的常量值为:")
fmt.Println(a)
fmt.Print("b的常量值为:")
fmt.Println(b)
}
Output:
2. In the const combination declaration of iota, each new line of iota+1 is added
The following code
package main
import "fmt"
const a = iota
const(
b = iota
c = iota
)
func main(){
fmt.Print("a的常量值为:")
fmt.Println(a)
fmt.Print("b的常量值为:")
fmt.Println(b)
fmt.Print("c的常量值为:")
fmt.Println(c)
}
Output
Second, the use of jump value
If you want to skip certain values, you can use _
to achieve it, which is _
equivalent to a trash can
package main
import "fmt"
const(
a = iota
b = iota
_
c = iota
)
func main(){
fmt.Print("a的常量值为:")
fmt.Println(a)
fmt.Print("b的常量值为:")
fmt.Println(b)
fmt.Print("c的常量值为:")
fmt.Println(c)
}
_
2 is received, so c should be 3 at this time
result
Third, the method of jumping the line
If you insert the assignment of other values in the const body, the count remains unchanged
package main
import "fmt"
const(
a = iota
b = 3.14
c = iota
)
func main(){
fmt.Print("a的常量值为:")
fmt.Println(a)
fmt.Print("b的常量值为:")
fmt.Println(b)
fmt.Print("c的常量值为:")
fmt.Println(c)
}
result
Four, one of the implicit use of expressions
In a const combination declaration, if no expression is specified, the nearest non-empty expression is used
The following code:
package main
import "fmt"
const(
a = iota * 2
b = iota * 3
c
d
)
func main(){
fmt.Print("a的常量值为:")
fmt.Println(a)
fmt.Print("b的常量值为:")
fmt.Println(b)
fmt.Print("c的常量值为:")
fmt.Println(c)
fmt.Print("d的常量值为:")
fmt.Println(d)
}
Where c and d will inherit the expression of iota*3
The results are as follows:
Five, the second method of implicit use of expressions
If there are multiple definitions in a row, there will be a one-to-one correspondence
The following code
package main
import "fmt"
const(
a,b = iota,iota+3
c,d
)
func main(){
fmt.Print("a的常量值为:")
fmt.Println(a)
fmt.Print("b的常量值为:")
fmt.Println(b)
fmt.Print("c的常量值为:")
fmt.Println(c)
fmt.Print("d的常量值为:")
fmt.Println(d)
}
Where a and b are in the same row, so at this time iota is both 0
At this time, c and d will correspond to the expressions of a and b, namely
c=iota
d=iota+3
The result is as follows
Refer to Introduction to
GO Language Grammar