What is the difference between a typed and an untyped constant when you assign or compare it?
Question 5MediumGo 1.22 to 1.25
A typed constant follows the same strict rules as a variable of that type. Go never converts between named types implicitly. An untyped constant can be assigned to any type that can represent its value.
const a = 10 // untyped integer
const b int = 10 // typed int
var f float64 = a // OK
// var g float64 = b // compile error: cannot use b (int) as float64
type Celsius float64
var c Celsius = a // OK
// var d Celsius = b // compile error
const big = 300
// var u uint8 = big // compile error: constant 300 overflows uint8
var r rune = 'a' + 1 // 'b'
Mixed expressions: if you combine an untyped constant with a typed operand, the constant is converted to that operand's type, and the compiler checks that the value fits. uint8(200) + 100 is a compile error (300 overflows uint8). var x uint8 = 200; x + 100 compiles and wraps around to 44 at run time.
Rule of thumb: keep constants untyped unless you want them tied to a domain type (enums, units). Give typed enum constants a named type so that mixing up kinds becomes a compile error.
More on Language Fundamentals & Types
- Q3What does this program print? (iota)
- Q4What are untyped constants? Explain why
const huge = 1 << 100compiles. - Q6Explain variable shadowing. Find the bug in this code.
- Q7What are the rules for
:=redeclaration, and why does this not compile? - Q8What does this print? (Assignment evaluation order)
- Q9What is the difference between a type conversion and a type assertion?