An example Analysis of the constant of Go language
Go language constant example analysis, many novices are not very clear about this, in order to help you solve this problem, the following small series will be explained in detail for everyone, there are people who need this can learn, I hope you can gain something.
overview
Golang is a cross platform nascent programming language. Today, Xiaobai will take everyone into Golang's world hand in hand. (Lesson 3)
constant
A constant is a fixed value that does not change during program execution. A constant can be any primitive data type. Such as integer constants, floating point constants, character constants, enumeration constants. Constants are generally treated as regular variables by compilers, except that their values cannot be modified after they are defined.
Format 1:
const Variable Name = Value
Format 2:
const variable name variable type
Examples:
package mainimport "fmt"func main() { //Method 1 const num1 = 1 //Method 2 const num2 int = 2 //debug output fmt.Println(num1, num2)}
Output:
1 2
Example 2:
package mainimport "fmt"func main() { //string constants const str1 = "I'm Little White" //integer constant const int1 = 1 //floating-point constants const float1 = 1.2 //Boolean type constant const boolean1 = true //debug output fmt.Println(str1) fmt.Println(int1) fmt.Println(float1) fmt.Println(boolean1)}
Output:
I'm Xiao Bai
1
1.2
true
constant calculation
Constants can be evaluated using len(), cap(), unsafe.Sizeof() functions. Constant expression function must be built-in function, otherwise compiled but.
Examples:
package mainimport "fmt"import "unsafe"//define constant const ( str = "iamlittlewhite" num = 1)func main() { //Calculate string length fmt.Println(len(str)) //Calculate integer bytes fmt.Println(unsafe.Sizeof(num))}
Output:
14
8
iota
iota is Go's constant counter and can only be used in constant expressions. iota is reset to 0 when the const keyword appears, and iota counts every new constant line in const. Iota can help us count how many times a constant has been accessed.
Examples:
package mainimport "fmt"func main() { //define iota const ( a = iota b = iota c = iota d = iota ) //debug output fmt.Println(a, b, c, d) fmt.Println(a, d)}
Output:
0 1 2 3
0 3
Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.