Day 005: Go language constants and iota

foreword

I majored in Java network security, but after participating in the internship (security research engineer), I found that most of the needs come from python and go, and Java also has but few. The company is more willing to accept handsome guys who can go, so I plan to take out one every day. Hour to learn the go language.
Please add image description


constant

In contrast to variables, constants are quantities that do not change. Once defined, it cannot be modified.
Constant keyword const.

const pi = 3.1415926

Bulk declaration:

const (
	status   = 200
	notfound = 404
)

When declaring constants in batches, if no value is written in a row, the default is the same as the previous row

const (
	n1 = 100
	n2
	n3
)

func main() {
    
    
	//pi = 123
	fmt.Println("n1:", n1)
	fmt.Println("n2:", n2)
	fmt.Println("n3:", n3)
}

insert image description here

iota

iota is a constant counter in golang and can only be used in constant expressions.

  • iota will be defined as 0 when const appears
  • const every new line of constant declaration will make iota count once
//iota
const (
	a1 = iota //0
	a2        //1
	a3        //2
)

func main() {
    
    
	//pi = 123
	fmt.Println("n1:", n1)
	fmt.Println("n2:", n2)
	fmt.Println("n3:", n3)

	fmt.Println("a1:", a1)
	fmt.Println("a2:", a2)
	fmt.Println("a3:", a3)
}

insert image description here

The iota function is similar to enumeration.

define order of magnitude

//定义数量级
const (
	_  = iota
	KB = 1 << (10 * iota)//1024
	MB = 1 << (10 * iota)
	GB = 1 << (10 * iota)
	TB = 1 << (10 * iota)
	PB = 1 << (10 * iota)
)

Guess you like

Origin blog.csdn.net/qq_53571321/article/details/123768771