In Go (Golang), the distinction between typed and untyped variables (or constants) is important for understanding how values are treated by the compiler.
1. Typed Variables
- A typed variable has an explicitly defined type at compile time.
- Once a type is assigned to a variable, it cannot hold values of a different type without explicit conversion.
- Typed variables are checked for type safety at compile time.
Example:
var x int = 42 // x is explicitly typed as `int`
var y float64 = 3.14 // y is explicitly typed as `float64`
In this case, x
can only hold integer values, and y
can only hold floating-point values.
2. Untyped Variables (or Constants)
- An untyped variable (or constant) does not have a specific type assigned to it at compile time.
- Instead, it has a default type that is inferred based on the context in which it is used.
- Untyped values are flexible and can be used in contexts where different types are expected, as long as they are compatible.
Example:
const z = 42 // z is an untyped constant
Here, z
is an untyped constant. Its type is not explicitly defined, so it can be used in various contexts where an int
, float64
, or other compatible types are expected.
Key Differences
Aspect | Typed Variables | Untyped Variables/Constants |
---|---|---|
Type Definition | Explicitly defined (e.g., int , float64 ) |
No explicit type; inferred from context |
Flexibility | Restricted to the declared type | Can be used in multiple type contexts |
Type Safety | Enforced at compile time | Flexible, but may lead to implicit conversions |
Example | var x int = 42 |
const z = 42 |
Example of Untyped Constants in Action
package main
import "fmt"
func main() {
const untypedConst = 42 // untyped constant
var a int = untypedConst // works: untypedConst is treated as int
var b float64 = untypedConst // works: untypedConst is treated as float64
fmt.Println(a, b) // Output: 42 42
}
In this example, untypedConst
is an untyped constant. It can be assigned to both int
and float64
variables without explicit conversion because its type is inferred based on the context.
Default Types for Untyped Constants
When an untyped constant is used in a context where a type is required, the compiler assigns it a default type based on its value:
- Integer literals:
int
- Floating-point literals:
float64
- Complex literals:
complex128
- Rune literals:
rune
(alias forint32
) - String literals:
string
Example:
const c = 42 // default type: int
const d = 3.14 // default type: float64
const e = "hello" // default type: string
Top comments (0)