Use of Golang—iota

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 constwill 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:

Insert picture description here

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

Insert picture description here

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
Insert picture description here

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

Insert picture description here

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:

Insert picture description here

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
Insert picture description here

Refer to Introduction to
GO Language Grammar

Guess you like

Origin blog.csdn.net/rjszz1314/article/details/109789317