Aman Goyal

LeetCode LeetCode

Understanding Constants in Go: Typed vs. Untyped (Kinds)


Understanding Constants in Go: Typed vs. Untyped (Kinds)

​In Go, constants are immutable values evaluated entirely at compile time. A crucial concept for moving from beginner to intermediate Go programmer is understanding the difference between typed and untyped constants.

1. Untyped Constants (The Default “Kind”)

​By default, any constant you declare without an explicit type is untyped. These constants don’t adhere to Go’s strict type system initially; instead, they possess a generic classification known as a “kind” (e.g., untyped integer, untyped float, untyped string).

​The primary benefits are arbitrary precision and flexibility:

const SpeedOfLight = 299792458 // Untyped integer kind

func main() {
	var i int = SpeedOfLight
	var i32 int32 = SpeedOfLight   // OK: Value fits in int32
	var f64 float64 = SpeedOfLight // OK: Value fits in float64
}

2. Typed Constants

​A constant becomes typed when you explicitly assign a type during its declaration. Typed constants are strictly bound by the Go type system rules from the moment they are declared.

const TypedSpeed int = 299792458 // Now has type 'int'

func main() {
	var i int = TypedSpeed         // OK
	// var i32 int32 = TypedSpeed  // ERROR: Cannot use type 'int' as type 'int32'
	var i32 int32 = int32(TypedSpeed) // OK: Explicit conversion required
}

Summary for Advanced Usage

​The “untyped constant kind” is a powerful language feature that simplifies numeric code. It allows you to define universal numeric values (like 𝜋 or physical constants) that can be reused across different numeric types (float32, float64, int, etc.) without type errors or messy conversions.

#Go #Programming #Constants #Typed Constants #Untyped Constants #Go Language #Software Engineering