Home »
Golang
Golang Constants
By IncludeHelp Last updated : October 05, 2024
Golang constants are the names of a fixed values. Constant's value cannot be changed.
How to declare constant in Golang?
To declare a constant in Golang, we use the const keyword followed by an identifier (constant name), type, and the constant value. The constant value must be assigned during the declaration of the constant.
Syntax
const constant_name type = constant_value
const constant_name = constant_value
Note: We can also omit the type during the constant declaration, the compiler assigns the type of the value to the constant.
Example of constant
package main
import (
"fmt"
)
const DEFAULT_NAME string = "Not available"
const DEFAULT_VALUE = 0
func main() {
fmt.Println("The value of DEFAULT_NAME is", DEFAULT_NAME)
fmt.Println("The value of DEFAULT_VALUE is", DEFAULT_VALUE)
}
Output
The value of DEFAULT_NAME is Not available
The value of DEFAULT_VALUE is 0
Declaring multiple constants
To declare multiple constants together – follow the below syntax,
Syntax
const (
DEFAULT_NAME string = "Not available"
DEFAULT_VALUE = 0
)
Example of declaring multiple constants
package main
import (
"fmt"
)
const (
DEFAULT_NAME string = "Not available"
DEFAULT_VALUE = 0
)
func main() {
fmt.Println("The value of DEFAULT_NAME is", DEFAULT_NAME)
fmt.Println("The value of DEFAULT_VALUE is", DEFAULT_VALUE)
}
Output
The value of DEFAULT_NAME is Not available
The value of DEFAULT_VALUE is 0
What happens if we don't assign the value while constant declaration?
If we don't assign the value to the constant while declaration, the constant will not be declared and the program will generate an error.
Example
package main
import (
"fmt"
)
const DEFAULT_NAME string
const DEFAULT_VALUE
func main() {
fmt.Println("The value of DEFAULT_NAME is", DEFAULT_NAME)
fmt.Println("The value of DEFAULT_VALUE is", DEFAULT_VALUE)
}
Output:
./prog.go:7:20: const declaration cannot have type without expression
./prog.go:7:20: missing value in const declaration
./prog.go:8:7: missing value in const declaration
./prog.go:11:46: undefined: DEFAULT_NAME
./prog.go:12:47: undefined: DEFAULT_VALUE
What happens if we change the value of a constant after the declaration?
We cannot change the value of a constant after declaring it. If we try to change the value of a constant after the declaration, the program will generate an error.
Example
package main
import (
"fmt"
)
const DEFAULT_NAME string = "Not available"
const DEFAULT_VALUE = 0
func main() {
fmt.Println("The value of DEFAULT_NAME is", DEFAULT_NAME)
fmt.Println("The value of DEFAULT_VALUE is", DEFAULT_VALUE)
DEFAULT_VALUE = 100
fmt.Println("The value of DEFAULT_VALUE is", DEFAULT_VALUE)
}
Output:
./prog.go:14:16: cannot assign to DEFAULT_VALUE (declared const)