This is a creation in Article, where the information may have evolved or changed.
Constant
Constants are the same as those in C #, and are created at compile time. Because the values must be determined at compile time, there are some limitations when declaring constants.
- The type must be: numeric value, String, Boolean
- The expression must be computable at compile time.
- Declaring a constant must be initialized at the same time that its value cannot be modified again
Doc
- Http://golang.org/doc/go_spec.html#Constants
- Http://golang.org/doc/go_spec.html#Constant_expressions
- Http://golang.org/doc/go_spec.html#Constant_declarations
- Http://golang.org//doc/go_spec.html#Iota
Grammar
The const keyword is used to declare constant const [(] name [data type] = expression [)] Const (multiple expressions that correspond to multiple constant names [data type]=)
If you define a multiline constant and the expression is consistent, you can omit the expression of the other row
When declaring without specifying a data type, the constant is an untyped constant
const Pi = 3.14159265358 //float64Pi=3.1415
Compile error: Cannot assign to pi, variable name pi is already in use there is no way to assign a value to pi again.
const a, b, c = 1, false, "str" //多重赋值
You can declare more than one constant at a time and assign a value at the same time, and its type can be inconsistent
const d = 1 << 2 //需计算的表达式复制可以是一个可以在编译期计算出结果的表达式const ( //批量声明 Monday, Tuesday, Wednesday = 1, 2, 3 Thursday, Friday, Saturday = 4, 5, 6 )
Bulk declaration of multiple constants
const e, f float64 = 1, 2 / 1.0
When declaring multiple variables, specify their data type, at which time both E and F are float64 data types
const g int ,h float64 = 1,2/1.0
Cannot specify data type separately, the data type needs to follow ' = ', compile error: syntax error:unexpected comma, expecting =
Iota
Use another constant iota counter in go, which can only be used in expressions of constants. Iota will be reset to 0 (before the first line of the const interior) when the const keyword appears, and each new line of constant declarations in the const will make the Iota count once (iota can be understood as the row index in the Const statement block). Using iota can simplify the definition and is useful when defining enumerations.
fmt.Println(iota)
Iota can only be used inside a const. Compilation Error: Undefined:iota
const a = iota // a=0const ( b = iota //b=0 c //c=1)
Iota counting starting from 0
const ( bit00 uint32 = 1 << iota //bit00=1 bit01 //bit01=2 bit02 //bit02=4 )
Iota can be in an expression (B=iota is also an expression)
const ( loc0, bit0 uint32 = iota, 1 << iota //loc0=0,bit0=1 loc1, bit1 //loc1=1,bit1=2 loc2, bit2 //loc2=2,bit2=4 )const ( e, f, g = iota, iota, iota //e=0,f=0,g=0 )
On the same line, iota the same
const ( h = iota //h=0 i = 100 //i=100 j //j=100 k = iota //k=3 )
Although only two iota are used, each new row of iota will be counted