0
0
Goprogramming~10 mins

Type inference in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Type inference
Declare variable with :=
Compiler infers type
Variable gets type automatically
Use variable in code
Program runs with inferred types
In Go, when you declare a variable using :=, the compiler automatically figures out the variable's type from the assigned value.
Execution Sample
Go
package main
import "fmt"
func main() {
  x := 42
  fmt.Println(x)
}
This code declares x with :=, so Go infers x is an int, then prints 42.
Execution Table
StepCode LineActionType InferredVariable Value
1x := 42Declare x with :=, compiler infers typeint42
2fmt.Println(x)Print value of xint42
3EndProgram ends--
💡 Program ends after printing the value; type inference done at declaration.
Variable Tracker
VariableStartAfter DeclarationFinal
xundefined42 (int)42 (int)
Key Moments - 2 Insights
Why don't we write the type explicitly when using :=?
Because the compiler infers the type from the assigned value at declaration, as shown in execution_table step 1.
Can the type of x change after declaration?
No, once inferred, the variable's type is fixed; x remains int as shown in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what type is inferred for x at step 1?
Afloat64
Bstring
Cint
Dbool
💡 Hint
Check the 'Type Inferred' column in execution_table row for step 1.
At which step does the program print the value of x?
AStep 2
BStep 1
CStep 3
DNo printing occurs
💡 Hint
Look at the 'Action' column in execution_table to find when fmt.Println is called.
If we change x := 42 to x := "hello", what type would be inferred?
Aint
Bstring
Cbool
Dfloat64
💡 Hint
Type inference depends on the assigned value's type, see execution_table step 1.
Concept Snapshot
Type inference in Go:
- Use := to declare and assign
- Compiler infers variable type automatically
- Type fixed after inference
- Simplifies code by skipping explicit types
Full Transcript
This example shows how Go infers the type of a variable when declared with :=. The compiler looks at the assigned value and decides the type automatically. Here, x is assigned 42, so x is an int. The program then prints x's value. The type stays fixed as int throughout. This makes code shorter and easier to write without losing type safety.