In Go programming, a constant is a simple constant value of the identifier, the program runs, the amount can not be modified.
Data type constant may be only boolean, numeric (integer, floating point and complex) and string.
Constant definition format:
const identifier [type] = value
It can omit the type specifier [type], because the compiler can infer the type based on the value of the variable.
Explicit typing:
const b string = "abc"
Implicit type definition:
const b = "abc"
More of the same type of statement can be abbreviated as:
const c_name1, c_name2 = value1, value2
The following examples demonstrate 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" // multiple assignment
area = LENGTH * WIDTH
fmt.Printf( "area:% d", area)
println()
println(a, b, c)
}
Examples of the above operating results are:
area: 50
1 false str
Constants can also be used to enumerate:
const (
Unknown = 0
Female = 1
Male = 2
)
Numbers 0, 1 and 2, respectively, on behalf of unknown gender, women and men.
Constants can use len(), cap(), unsafe.Sizeof().
package main
import "unsafe"
const (
a = "abc"
b = len(a)
c = unsafe.Sizeof(a)
)
func main() {
println(a, b, c)
}
Examples of the above operating results are:
abc 3 16
Top comments (0)