Check constant representability and default types
A constant must fit its destination
Representability means a constant can be represented by the destination type under Go’s rules. An integer constant must fit the integer range and have no fractional part. Floating-point constants may be rounded to the destination precision, but must not overflow. An untyped constant can adapt to a compatible destination.
package main
import "fmt"
func main() { const amount = 100 var small uint8 = amount var large int64 = amount fmt.Printf("%T %v\n", small, small) fmt.Printf("%T %v\n", large, large)}The output shows uint8 100 and int64 100. Both types can represent 100. In Printf, %T prints the type of the supplied value and %v prints its value; the newline escape ends the line. var small uint8 = 256 fails because the constant exceeds 255.
Default types
package main
import "fmt"
func main() { n := 12 fraction := 1.5 letter := 'A' signal := 2i fmt.Printf("%T %T %T %T\n", n, fraction, letter, signal)}The output is int float64 int32 complex128. The default types for untyped boolean, rune, integer, floating-point, complex and string constants are bool, rune, int, float64, complex128 and string respectively. rune is an alias of int32, so %T reports int32 here. A constant too large for int can fail a short declaration even if it fits uint64; give the variable a suitable explicit type. A typed constant does not adopt a different type merely because its value fits.
Try it locally
Use the untyped constant score = 200 to initialize a uint8 and an int32 variable. Print their types and values with Printf. Expected lines: uint8 200 and int32 200.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constants and Basic Types 05: Check constant representability and default types
Check the lesson objective before moving on.
What type does x := 1.5 infer?
Which declaration fails?