Declare typed and untyped constants in Go
A value that cannot be reassigned
A constant is a named compile-time value. Declare it with const name = expression or const name type = expression. Constants may represent boolean, string, integer, floating-point or complex values. Unlike a variable, a constant cannot be reassigned. An untyped constant has a kind but no fixed Go type until a context requires one. A typed constant already has a declared type.
package main
import "fmt"
func main() { const limit = 12 const port uint16 = 8080 fmt.Println(limit, port)}The output is 12 8080. limit is an untyped integer constant and port is a typed uint16 constant. A representable untyped constant can be used in different numeric contexts, while typed constants follow normal typed assignment rules.
Constant expressions
package main
import "fmt"
func main() { const ( minutesPerHour = 60 hoursPerDay = 24 minutesPerDay = minutesPerHour * hoursPerDay ) fmt.Println(minutesPerDay)}The output is 1440. The multiplication of two integer constants is evaluated as a constant expression. A normal function call or an expression depending on an ordinary variable cannot initialize a constant. For example, after n := 5, const twice = n * 2 is invalid. Use a variable when the value is calculated from changing data.
Try it locally
Declare an untyped constant itemsPerBox = 6 and a typed int constant boxes = 4. Declare total as their constant product and print it. Expected: 24.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constants and Basic Types 04: Declare typed and untyped constants in Go
Check the lesson objective before moving on.
Which declaration creates an untyped constant?
After n := 5, why is const x = n invalid?