In Go, variables can be declared in two ways: static type declaration and dynamic type declaration.
Static Type Declaration
Static type declarations specify the variable's type at compile time, which remains fixed during runtime. Go is a statically typed language where every variable explicitly has a type. Static type declarations provide type safety, allowing type errors to be caught during compilation.
Examples:
govar age int = 30
In this example, age is declared as an int type, meaning any value assigned to age must be of integer type. If an attempt is made to assign a non-integer value, such as a string or float, to age, the compiler will throw an error.
Dynamic Type Declaration
Although Go is inherently a statically typed language, it supports a form of dynamic typing through interfaces. When using interface types, the type of values stored in interface variables can be dynamically changed at runtime.
Examples:
govar x interface{} x = 20 // At this point, x is of int type x = "hello" // Now x is of string type
In this example, x is declared as interface{} type, which is an empty interface that can accept values of any type. Initially, an integer is assigned to x, and then a string is assigned to x. This approach is similar to how variable types are used in dynamically typed languages, but type checking is still performed at compile time through interfaces.
Summary
Overall, Go is primarily statically typed, but by using the empty interface (interface{}), it can simulate dynamic typing behavior. This allows Go to maintain the safety of statically typed languages while providing the flexibility of dynamically typed languages when necessary.