May 11, 2021 Go
A constant is an identifier of a simple value that is not modified while the program is running.
The data types in a constant can only be Boolean, numeric (integer, float, and complex), and string.
The definition format of the constant:
const identifier [type] = value
You can omit the type descriptor because the compiler can infer its type based on the value of the variable.
const b string = "abc"
const b = "abc"
Multiple declarations of the same type can be short to:
const c_name1, c_name2 = value1, value2
The following example demonstrates the application of constants:
package main import "fmt" func main() { const LENGTH int = 10 const WIDTH int = 5 var area int const a, b, c = 1, false, "str" //多重赋值 area = LENGTH * WIDTH fmt.Printf("面积为 : %d", area) println() println(a, b, c) }
The above examples run as:
面积为 : 50 1 false str
Constants can also be used as enumerity:
const ( Unknown = 0 Female = 1 Male = 2 )
The numbers 0, 1, and 2 represent unknown genders, women, and men, respectively.
Constants can be used with len(), cap(), unsafe. T he Sizeof() constant evaluates the value of the expression. In a constant expression, the function must be a built-in function, otherwise it cannot be compiled:
package main import "unsafe" const ( a = "abc" b = len(a) c = unsafe.Sizeof(a) ) func main(){ println(a, b, c) }
The above examples run as:
abc 3 16
iota, a special constant, can be thought of as a constant that can be modified by the compiler.
Each time the const keyword appears, it is reset to 0, and then before the next const appears, the number it represents is automatically increased by 1 for each iota that appears.
iota can be used as an enumeration value:
const ( a = iota b = iota c = iota )
The first iota is equal to 0, and whenever iota is used on a new line, its value is automatically added by 1;
const ( a = iota b c )
package main import "fmt" func main() { const ( a = iota //0 b //1 c //2 d = "ha" //独立值,iota += 1 e //"ha" iota += 1 f = 100 //iota +=1 g //100 iota +=1 h = iota //7,恢复计数 i //8 ) fmt.Println(a,b,c,d,e,f,g,h,i) }
The above examples run as:
0 1 2 ha ha 100 100 7 8
Take another interesting example of iota:
package main import "fmt" const ( i=1<<iota j=3<<iota k l ) func main() { fmt.Println("i=",i) fmt.Println("j=",j) fmt.Println("k=",k) fmt.Println("l=",l) }
The above examples run as:
i= 1 j= 6 k= 12 l= 24
iota means that 1 is automatically added from 0, so i=1=lt;lt;0,j=3<?lt;1 (i.e., i=1,j=6, this is no problem, the key is in k and l, from the output results, k=3<lt;2, l=3<lt;3.