Declaring Constants
The declaration of constants is similar to that of variables. The keyword var
is replaced with the keyword const
.
Note: Constants must be assigned a value when declared.
In Go, all variables must be used after they are defined, but constants are an exception. Even if they are not used, there will be no error.
The syntax for declaring a constant is as follows:
const name [type] = value
name
is the name of the constant being declared. type
is the data type of the constant, but it can be omitted because Go can infer it automatically. The value at the end is the value assigned to the constant.
Note that only the following types can be used for constant declarations:
- Integer types
- Floating-point types
- Complex types
- Boolean types
- String types
Let's look at an example. Create a new file called const.go
in the ~/project
directory:
touch ~/project/const.go
Enter the following code in const.go
:
package main
import "fmt"
// Declare a single constant labex
const labex string = "LabEx" // explicitly specify the type as string
const shiyanlou = "SHIYANLOU" // automatically inferred as string by the compiler
// Declare multiple constants
const hangzhou, chengdu = "HANGZHOU", "CHENGDU"
const (
monday = "MONDAY"
thesday = "THESDAY"
wednesday = "WEDNESDAY"
)
func main() {
fmt.Printf("The type of labex is: %T, and its value is %s\n", labex, labex)
fmt.Printf("The type of shiyanlou is: %T, and its value is %s\n", shiyanlou, shiyanlou)
fmt.Println()
fmt.Println(hangzhou, chengdu)
fmt.Println(monday, thesday, wednesday)
}
After running the program, the output is as follows:
The type of labex is: string, and its value is LabEx
The type of shiyanlou is: string, and its value is SHIYANLOU
HANGZHOU CHENGDU
MONDAY THESDAY WEDNESDAY
Here, we demonstrate the declaration of single and multiple constants. When declaring multiple constants, it is recommended to use parentheses.
In the program, we only demonstrate the declaration of string constants. However, constants can also have other types, such as integers and booleans.
When declaring multiple constants using parentheses, if a constant is not initialized, its value will be the same as the value on the previous line.
Enter the following code in const.go
:
package main
import "fmt"
const (
monday = "MONDAY"
thesday = "THESDAY"
wednesday = "WEDNESDAY"
thursday
friday
)
func main() {
fmt.Println(monday, thesday, wednesday, thursday, friday)
}
The output is as follows:
MONDAY THESDAY WEDNESDAY WEDNESDAY WEDNESDAY
As you can see, the constants thursday
and friday
were declared without specific values and their output is the same as the previous constant, "WEDNESDAY".