In Go, type inference refers to the ability of the compiler to automatically determine the data type of a variable based on its assigned value. Instead of explicitly specifying the type, you can use the shorthand declaration :=
to let the compiler infer the type for you.
Here’s an example that demonstrates type inference in Go:
package main
import "fmt"
func main() {
// Type inference with shorthand declaration
message := "Hello, World!"
count := 10
isActive := true
pi := 3.14
// Print the values and types of the variables
fmt.Printf("Message: %s (%T)\n", message, message)
fmt.Printf("Count: %d (%T)\n", count, count)
fmt.Printf("IsActive: %t (%T)\n", isActive, isActive)
fmt.Printf("Pi: %f (%T)\n", pi, pi)
}
In the above code, we use the shorthand declaration :=
to declare and initialize variables without explicitly specifying their types. The compiler infers the types based on the assigned values:
- The variable
message
is inferred as astring
because it is assigned a string value ("Hello, World!"
). - The variable
count
is inferred as anint
because it is assigned an integer value (10
). - The variable
isActive
is inferred as abool
because it is assigned a boolean value (true
). - The variable
pi
is inferred as afloat64
because it is assigned a floating-point value (3.14
).
We then use the fmt.Printf
function to print the values and types of the variables. The %s
, %d
, %t
, and %f
are format verbs used to specify the types of the variables in the formatted output.
Type inference in Go reduces the need for explicit type declarations, making the code more concise and readable. However, it’s important to note that once a variable’s type is inferred, it cannot be changed. If you need to change the type of a variable, you must re-declare it with the desired type.