In a Go program, we can use a const
block for a constant value. A const
can never be reassigned. And its name will help us identify its meaning.
This keyword can optionally be used with the iota
keyword, which can generate sequential values. This reduces possible issues with typos.
This example introduces the const
keyword in a block of enumerated constants. We do not use all the features of const
here. We declare 3 names and give them values.
const
creation. The Go compiler starts iota
at 0 and increments it by one for each following constant.package main import "fmt" const ( Cat = 10 Dog = 20 Bird = 30 ) const ( Low = 5 * iota Medium High ) func main() { // Use first const values. fmt.Println(Cat, Dog, Bird) // Use our iota constants. fmt.Println(Low, Medium, High) }10 20 30 0 5 10
const
A constant name cannot be assigned to another value. It is not a variable. The Go compiler will report an error here. With var
, the program will compile.
package main const ( Normal = 1 Medium = 2 ) func main() { Medium = 3 }C:\programs\file.go:13: cannot assign to Medium
const
syntaxA constant can be declared in a single-line statement. We can also specify constants within func
bodies. Here we create a constant string
of value "Blue."
package main import "fmt" func main() { // Use a constant string in a func. const color = "Blue" // Test the constant. if color == "Blue" { fmt.Println(color) } }Blue
We can declare multiple consts on one line. No parentheses are required. Here we have a const
string
and a const
untyped integer.
const
integer value is untyped. A type like int64
can be specified.package main import "fmt" func main() { // Declare multiple consts on one line. const name, size = "carrot", 100 // Display values. fmt.Println(name) fmt.Println(size) }carrot 100
int16
A const
can be typed. Here we specify the type int16
for the const
"v." We add the int16
to a slice of int16
elements.
int16
or other integral values.package main import "fmt" func main() { // A const can have an explicit type. const v int16 = 10 // Create a slice with the constant int16. slice := []int16{v, 10} fmt.Println(slice) }[10 10]
Sometimes using a type on an integer constant will cause an error. The type must be correct for the rest of the program. Otherwise the program will not compile.
package main import "fmt" func main() { const v int32 = 1000 // The const int32 cannot be used in an int16 slice. slice := []int16{v, 10} fmt.Println(slice) }cannot use v (type int32) as type int16 in array element
With const
typed integers, overflow is detected at compile-time. Here we try to use an invalid number in an int16
. The program never reaches execution.
package main import "fmt" func main() { // We cannot have an int16 with this value. const v int16 = 1000000 // Not reached. fmt.Println(v) }constant 1000000 overflows int16
The const
keyword allows us to pull known constants into separate parts in our Go code. We can reference the constants wherever needed, which reduces bugs.