ProgramGuru

Type Inference

Start with Go Type Inference

Type inference lets Go determine a variable’s type from the expression used to initialize it. This avoids repeating obvious type names without giving up static checking.

What you’ll learn

  • Explain compile-time inference.
  • Predict default types for common literals.
  • Know when to specify a type explicitly.

Understand the idea

With n := 12, the default type for an untyped integer constant is int. With x := 1.25 it is usually float64; with s := "Go" it is string. The resulting variable still has a fixed type.

Inference is different from dynamic typing. Once n is an int, writing n = "twelve" is a compile-time error. You can use explicit declarations when a specific type is required.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	count := 12
	price := 2.5
	label := "tickets"
	fmt.Printf("%T %T %T\n", count, price, label)
}

Output

int float64 string

Trace what the program does

The literals supply enough information for the compiler to assign a type to each variable. %T reveals those inferred types at runtime, but inference itself happens during compilation.

Avoid common mistakes

  • Type inference does not permit later assignment of unrelated types.
  • Use var n int64 = 12 when a specific width is required rather than relying on the default int.

Try it yourself

Change count := 12 to var count int64 = 12 and check how the printed type changes.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Does type inference make Go dynamically typed?
Choose one answer. You can try again.

Answer and explanation

No, inferred variables still have compile-time types

Correct. The literals supply enough information for the compiler to assign a type to each variable.

What you should remember

You have practiced Go Type Inference in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Type Conversion →