The declaration of a constant is similar to that of a variable, but using the const keyword. The definition format of a constant is similar to the declaration syntax of a variable:
const name type = value
Constants can be characters, strings, booleans, or numbers.
Constants cannot be declared with the := syntax, but the type can be omitted because the compiler can infer its type based on the value of the variable.
// Explicit typed definition
const PI float64 = 3.1415926
// Implicitly typed definition
const PI = 3.1415926
Like variable declarations, multiple constants of different types can also be declared together:
const (
b bool = true
pi float = 3.1415926
)
The following is a complete code example.
package main
import "fmt"
const Pi = 3.1415
func main() {
const World = "世界"
fmt.Println("Hello", World)
fmt.Println("Happy", Pi, "Day")
const Truth = true
fmt.Println("Go rules?", Truth)
}
Below is the program output:
Hello 世界
Happy 3.1415 Day
Go rules? true