Go

What are untyped constants? Explain why const huge = 1 << 100 compiles.

Question 4HardGo 1.22 to 1.25

Untyped constants are exact values that live only at compile time. The spec requires at least 256 bits of precision for integer constants. A constant only gets a concrete type when it is used somewhere that needs one. If nothing gives it a type, it takes its default type: int, float64, rune, complex128, string or bool.

const huge = 1 << 100          // fine: exact value, no type yet
fmt.Println(huge >> 98)       // 4: the result fits in int
// fmt.Println(huge)          // compile error: constant overflows int

const third = 1.0 / 3
var f32 float32 = third        // no conversion needed
var f64 float64 = third

fmt.Println(1 / 2)             // 0   (both operands are untyped integer)
fmt.Println(1 / 2.0)           // 0.5 (untyped float)

var d time.Duration = 5 * time.Second // 5 is untyped, so it adapts
_ = d
n := 5
// _ = n * time.Second        // compile error: mismatched types int and time.Duration
_ = time.Duration(n) * time.Second

Gotcha: x := 1 << 100 fails to compile, because the default type int can't hold the value. Constant expressions are also evaluated exactly, so 0.1 + 0.2 == 0.3 is true for constants but false for float64 variables.

What the interviewer wants to hear: untyped constants are why you can write time.Sleep(2 * time.Second) without a cast, and why a variable of type int needs an explicit conversion in the same spot.

More on Language Fundamentals & Types

All 39 Language Fundamentals & Types questions